behzad
709
10
Laravel

Bind posted data to a model in Laravel 5.4

Posted 2 years ago by behzad

So in Laravel 5.4 Route Model Binding, we can bind a route to a model like:

define the route in web.php:

web.php:

Route::get('/users/{user}', [email protected]);

[email protected]:

public function show(User $user){
    // now we already have access to $user because of route model binding
    // so we don't need to use User::find($user), we just return it:
    return view(users.show, compact('user'));
}

The above code will work just fine, so in our controller we can return the $user without finding the user, we already have it.

but imagine this:

web.php:

Route::patch('/users/archive', [email protected]);

EDITED: now the above line makes a patch route and we don't have {user} in the route url, the user id is being posted via the form.

[email protected]:

public function archive(Request $request, User $user){
    // how can I access the $user here without using User::find($user);
    // I get to this action via a form which is posting `user` as a value like `5`
    dd($request->user); // this now echo `5`
    // I can do:
    // $user = User::find($request->user);
    // and it works, but is there a way to not repeat it every time in every action
}

I would appreciate any kind of help.

EDIT: It seems it's not called Route Model Binding anymore since we don't have the {user} in the route and that's because my code is not working, the user variable is being posted to the controller and it's only accessible via $request->user.

this is route model binding:

Route::patch('users/{user}/archive', [email protected]);

this is not:

Route::patch('users/archive', [email protected]);

since we don't have {user} and it's being posted via the form and could be accessed only via $request->user. (please correct me if I am wrong about the definition of route model binding)

SO:

what I want to achieve in a nutshell: in every request being sent to my UsersController, if I am sending user variable as a post variable, it must be bounded to User::findOrFail($request->user) and then $user must be available in my controller actions.

I want to achieve this because in every action I am repeating myself doing User::findOrFail($request->user) and I don't want to do that, so I want to check in every request if I have a variable name like a model name, they should be bounded.

Please sign in or create an account to participate in this conversation.