【发布时间】:2022-01-21 22:37:13
【问题描述】:
我不确定我做错了什么,但我有一个自定义表单请求验证,我正在使用它来创建和更新具有唯一列验证的记录。它可以很好地创建新记录,但不能用于更新记录。
客户表单请求
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ServiceTypeRequest extends FormRequest
{
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'service_name' => ['required', Rule::unique('service_type', 'Service')->ignore($this->service_type) ],
'type' => ['required', 'string'],
'view_availability' => ['required', 'boolean'],
];
}
}
控制器更新
public function update(ServiceTypeRequest $request, ServiceType $serviceType)
{
$validated = $request->validated();
$service_type = ServiceType::update([
'Service' => $validated['service_name'],
'type' => $validated['type'],
'view_availability' => $validated['view_availability'],
]);
return redirect()
->route('service_type.index')
->with('status', 'Service type updated!');
}
使用 PUT 方法提交更新表单时出错它抱怨 $this 我在 service_name 的自定义表单验证中有这个。
Error
Using $this when not in object context
http://localhost:8021/service_type/58
【问题讨论】:
-
试试 ->ignore($this->get('service_type'))
-
这不是一个静态方法,所以它是在一个对象上下文中......是错误所说的那一行造成的吗?
-
错误消息为您提供堆栈跟踪;你的代码中一定有你调用
ServiceTypeRequest::rules()的地方。另外值得注意的是,无效数据永远不会到达您的控制器,因此调用$request->validated()是没有意义的。 -
现在您正在检查
$request->service_name的值是否与service_type表的Service列中的值匹配,但忽略id列相等的任何记录到$request->service_type。那是对的吗?如果是这样,您的数据库设置非常非常规。在 SQL 术语中,如果SELECT COUNT(*) FROM service_type WHERE Service = '$request->service_name' AND id != '$request->service_type';返回 > 0,则验证失败。 -
最后一点,
ServiceType::update()将更新数据库中的每一行。我假设你想改用$serviceType->update()?