Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

model binding with controller function laravel routing

Tags:

php

laravel-5

hello I'm using laravel 5.4, and I would use a model binding in my routing. But I would use a controller function:

Route::get('/user/{id}', 'usersController@show');

But I would use a model binding so in my controller I would do something like:

public function show(Request $request, User $user){
    dd($user->id)
}

But now $user->id is null because I don't know how binding model and use a controller function. I tried with:

Route::model('user', 'User');

But It doesn't work.

Is it possible?

like image 313
LorenzoBerti Avatar asked Mar 09 '23 00:03

LorenzoBerti


1 Answers

Well from the Laravel Manual you don't need the Route::model('user', 'User');, Laravel does that for you :

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.

So just change this line:

Route::get('/user/{user}', 'usersController@show');

And since you're using the type hint for the variable, Laravel will automatically bind it to the user model.

like image 72
teeyo Avatar answered Mar 20 '23 16:03

teeyo