简体   繁体   中英

(laravel) Is it possible to use method injection by passing a field other than the id?

I'm kinda new to Laravel, and trying to get the most from it's method (dependency) injejction whilst also aiming to keep a good url structure (for the SEO).

Here's the case: I'm calling a route with a variable appended to it's end, like this: www.mywebsite.com/user/id

And that's addressed to a controller with a method like so:

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

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

But in the aims of having a better SEO, I need to change that url to somewhat like this: www.mywebsite.com/users/nickname.

Is it possible to use method injection in a way similar to what I'm currently using, but using another field (in this case, the nickname) other than the id, to get a User object from the database?

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

I could do it manually, but I want to get the most out of Laravel.

Thank you for your time, and also, I'm studying english, so if you are a native english speaker or fluent on it, I'll appreciate if you point me out my grammar mistakes (briefly without distorting the post).

Bruno

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM