4

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?

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

0

In Laravel 10, you could also do the blow

<?php
use App\Models\User;

Route::get('/user/{user:nickname}', function (User $user) {
    return $user;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.