Amr Monier
Amr Monier

Reputation: 3

Route Model binding fails when using Form request

The Route model binding fails when I use the FormRequest to validate the request. To be more specific, when I try to access the parameters in the form request and give the following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name:\"moniersa\"' in 'where clause' 
(SQL: select count(*) as aggregate from `users` where `email` = [email protected] and 
`name:\"moniersa\"` <> {\"id\":5 and `email:\"a`.`monier2130@gmail`.`com\"` = 
email_verified_at:null and `admin:1` = verified:0 and `created_at:\"2020-02-11 22:33:33\"` = 
updated_at:\"2020-02-11 23:17:40\"})

The code of the update method:

public function update(User $user, UpdateUserRequest $request)
    {
        $data = $this->extract_data($request);
        $user->update($data);
        return response()->json(['data' => $user], 200);
    }

The code of the rules function in the Update request:

public function rules()
    {
        return [
            'name' => 'required|string|min:3|max:40',
            'email' => 'required|email|unique:users,email,' . $this->user,
            'password' => 'required|string|min:9|confirmed'
        ];
    }

Whenever, I remove the User hint from the update method or $this->user from the update request file, everything works fine. Any clue about what is the problem is?

Upvotes: 0

Views: 366

Answers (1)

Andy Song
Andy Song

Reputation: 4684

Route model binding means you do not need to use $user = User::findOrFail($user); anymore,

public function update(User $user, UpdateUserRequest $request)
    {

        $user = User::findOrFail($user);// this line is redundant, you can remove it.
        $data = $this->extract_data($request);
        $user->update($data);
        return response()->json(['data' => $user], 200);
    }

Upvotes: 2

Related Questions