验证函数期望第一个参数作为请求输入数组,而不是请求对象。以下代码将正常工作。
这是我的代码:
public function update(User $user)
{
$this->validate(request(), [
'name' => 'required|min:3|max:50|unique:users,name,' . $user->id,
'email' => 'required|email|max:255|unique:users,email,' . $user->id,
'origin' => 'max:50',
'about' => 'max:5000',
]);
$user = User::find($user);
$user->name = request('name');
$user->original = request('origin');
$user->email = request('email');
$user->about = request('about');
$user->save();
return back();
}
我得到这个错误:
IlluminateDatabaseQueryException
SQLSTATE[HY093]: Invalid parameter number (SQL: select * from .... ?))
错误可能源于$user = User::find($user);
。
由于您使用的是Route模型绑定,因此不需要再次加载User
:
public function update(User $user)
{
$this->validate(request(), [
'name' => 'required|min:3|max:50|unique:users,name,' . $user->id,
'email' => 'required|email|max:255|unique:users,email,' . $user->id,
'origin' => 'max:50',
'about' => 'max:5000',
]);
$user->name = request('name');
$user->original = request('origin');
$user->email = request('email');
$user->about = request('about');
$user->save();
return back();
}
$this->validate (request()->all(), $rules)
您还可以为验证消息传递第三个参数。