laravel request validation on updating of data

2019-08-14 07:45发布

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条回答
女痞
2楼-- · 2019-08-14 08:18

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.

查看更多
登录 后发表回答