laravel request validation on updating of data

2019-08-14 07:22发布

问题:

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

回答1:

To fix the issue, we need to understand the error first:

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.

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);
}

Or simply:

$user->save();
return new UserResource($user);

Because we expect exception to be thrown on validation error.