Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customizing route model binding key

I'm calling a route with a variable appended to it's end, like this:

Route::get('/user/{user}', 'UserController@listUser');

That points to a controller with a method like so:

public function listUser(User $user){
   dd($user);
}

That's working just fine; if I go to www.example.com/user/3, Laravel will automatically fetch me the user with id = 3

But I need to change that URL to something like this: www.example.com/users/nickname using a different property of the User model.

If that's possible, how can I do it?

like image 653
Bruno García Avatar asked Nov 16 '25 15:11

Bruno García


1 Answers

In this case you need to define in your User Eloquent model the following method:

public function getRouteKeyName()
{
    return 'nickname';
}

You can read more about it in Route Model binding documentation.

like image 57
Marcin Nabiałek Avatar answered Nov 18 '25 06:11

Marcin Nabiałek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!