laravel请求验证数据更新 [英] laravel request validation on updating of data
问题描述
我有一个请求验证,用于我的数据更新
I have a request validation for my updating of data
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' = 'required|string|email|max:255|unique:users,email,'.$this->id,
'password' => 'min:6',
];
}
这是我的控制器
public function update(UpdateUserInfo $request, $id){
$user = User::findOrFail($id);
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->role_id = 2;
if($request->input('password')){
$user->password = Hash::make($request->input('password'));
}
return $user->save() ?: new UsersResource($user);
}
但是我有一个错误提示The Response content must be a string or object implementing __toString(), "boolean" given.
However i have an error saying The Response content must be a string or object implementing __toString(), "boolean" given.
在我进行验证之前,是在控制器本身上
Before my validation is on the controller itself
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users,email,'.$id,
'password' => 'min:6',
]);
$user = User::findOrFail($id);
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->role_id = 2;
if($request->input('password')){
$user->password = Hash::make($request->input('password'));
}
if($user->save()){
return new UserResource($user);
}
}
,它工作正常.现在,我只想将验证与控制器分开.
and it is working fine. And right now i just want to separate the validation from the controller.
我认为问题出在电子邮件的验证上
I think that the problem is on the validation of email
'email' = 'required|string|email|max:255|unique:users,email,'.$this->id,
但是我不知道如何通过更新方法传递ID
but i dont know how to pass the id from the method of update
推荐答案
要解决此问题,我们需要先了解该错误:
To fix the issue, we need to understand the error first:
响应内容必须是实现的字符串或对象 __toString(),给出布尔值".
The Response content must be a string or object implementing __toString(), "boolean" given.
这表明问题出在控制器的响应(返回)上.
It indicates that the problem is in the response (return) of your controller.
由于$user->save()
成功返回true
,因此此行会导致您的控制器在更新成功时返回布尔值,而Laravel期望string or object implementing __toString()
:
Since $user->save()
returns true
on success, this line causes your controller return boolean when the update success while Laravel expects string or object implementing __toString()
:
return $user->save() ?: new UsersResource($user);
因此,您可以尝试解决此问题的方法是简单地还原以前的返回值(您可以保留其余代码):
So what you can try to fix this is by simply restoring the previous return (you can keep the rest of the code):
if($user->save()){
return new UserResource($user);
}
或者简单地:
$user->save();
return new UserResource($user);
因为我们希望验证错误会引发异常.
Because we expect exception to be thrown on validation error.
这篇关于laravel请求验证数据更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!