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',
];
}
this is my controller
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);
}
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,
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:
It indicates that the problem is in the response (return) of your controller.
Since
$user->save()
returnstrue
on success, this line causes your controller return boolean when the update success while Laravel expectsstring or object implementing __toString()
:So what you can try to fix this is by simply restoring the previous return (you can keep the rest of the code):
Or simply:
Because we expect exception to be thrown on validation error.