如何验证更新 laravel 中的唯一电子邮件和唯一名称?
how validate unique email and unique name in update laravel?
这是我的代码:
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();
}
我收到这个错误:
Illuminate\Database\QueryException
SQLSTATE[HY093]: Invalid parameter number (SQL: select * from .... ?))
验证函数期望第一个参数作为请求输入数组而不是请求对象。以下代码可以正常工作。
$this->validate (request()->all(), $rules)
您还可以为验证消息传递第三个参数。
错误可能源于$user = User::find($user);
。
由于您正在使用 Route model binding,因此您不需要再次加载 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();
}
这是我的代码:
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();
}
我收到这个错误:
Illuminate\Database\QueryException
SQLSTATE[HY093]: Invalid parameter number (SQL: select * from .... ?))
验证函数期望第一个参数作为请求输入数组而不是请求对象。以下代码可以正常工作。
$this->validate (request()->all(), $rules)
您还可以为验证消息传递第三个参数。
错误可能源于$user = User::find($user);
。
由于您正在使用 Route model binding,因此您不需要再次加载 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();
}