【问题标题】:How to pass id to Form Request in Laravel如何将 id 传递给 Laravel 中的表单请求
【发布时间】:2020-08-14 07:17:43
【问题描述】:

我正在尝试更新数据库中的一条记录,并且我正在使用表单请求来验证唯一字段,但我无法将 id 传递给该表单,因为我只是使用这样的路由:

Route::resource('ganado/engorde', 'GanadoController')->middleware('auth');

在我的更新控制器中:

public function update(GanadoEditFormRequest $request, $id)
{
    $bovino = Ganado::findOrFail($id);
    ...
}

这是我的表单请求:

public function rules()
{
    return [
        'codigo_ganado' =>  ['required', 

            Rule::unique('ganado')
                   ->ignore($this->id, 'id_ganado')
                   ->where('lote_actual', $this->lote_actual)
                   ->where('ganaderia', $this->ganaderia)
            ],
    ];
}

我尝试直接传递 id = "85" 只是为了检查这个“忽略”的东西是否正常工作并且我也得到了错误=

id 85 而不是 id = 85。

如何正确忽略当前的更新记录?

编辑:

这是我的“Ganado”表:

【问题讨论】:

  • 您是否使用过类似url.com/ganado/engorde/85 的方式来查找您的商品?
  • 是的,我的更新控制器工作正常,这是一个例子:http://ganaderia.test/ganado/engorde/85/edit@Atlas-Pio

标签: laravel eloquent


【解决方案1】:

因为我不知道你的代码是什么样的,你可能想试试这个:

public function rules()
{
      $id = $this->route('id')
      // Or
      $id = $this->route('engorde')  
    return [
        'codigo_ganado' =>  ['required', 

            Rule::unique('ganado')
                   ->ignore($id, 'id_ganado')
                   ->where('lote_actual', $this->lote_actual)
                   ->where('ganaderia', $this->ganaderia)
            ],
    ];
}

因此,根据您的Ganado 表,您的主表是id_ganado,laravel 始终将带有id 的表识别为主表,因此您可能需要添加

protected $primaryKey = 'id_ganado';

编辑:更新为ignore($id.',id_ganado')

【讨论】:

  • 好的第二个它正在工作并且我正在获取 id,但仍然得到唯一的验证消息,只是为了检查我是否得到了 id 我删除了 'id_ganado' 以获取 id 列的 sql 错误未知,在这里我可以检查我是否获得了 id,为什么仍然无法忽略当前记录?
  • 这是我说的错误:Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select count(*) as aggregate from ganado where codigo_ganado = 0604 and id <> 85 and lote_actual = Lote-1 and ganaderia = VS) 只是为了检查我是否获得了正确的 id
  • 是的,这就是为什么我在后面的问题中问这个问题,因为我尝试直接传递 id 只是为了检查它是否正常工作并且它不工作。已经用表格更新了问题。
  • 已经在我的模型@Atlas-Pio 中以这种方式定义了主键
  • 嗯,你的意思是 -> 在忽略词之后?因为那是错误的表达方式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-18
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-05
相关资源
最近更新 更多