简体   繁体   English

(laravel)是否可以通过传递除id之外的字段来使用方法注入?

[英](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). 我是Laravel的新手,并试图从它的方法(依赖)注入中获得最大的收益,同时也旨在保持一个良好的网址结构(对于搜索引擎优化)。

Here's the case: I'm calling a route with a variable appended to it's end, like this: www.mywebsite.com/user/id 情况就是这样:我正在调用一个附加了变量的路径,如下所示: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 如果我去www.mywebsite.com/user/3,Laravel将自动获取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. 但是为了拥有更好的搜索引擎优化,我需要将这个网址更改为: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? 是否可以以类似于我当前使用的方式使用方法注入,但是使用除id之外的另一个字段(在本例中为昵称)来从数据库中获取User对象?

If that's possible, how can I do it? 如果可能,我该怎么办?

I could do it manually, but I want to get the most out of Laravel. 我可以手动完成,但我希望从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: 在这种情况下,您需要在User Eloquent模型中定义以下方法:

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

You can read more about it in Route Model binding documentation. 您可以在Route Model绑定文档中阅读有关它的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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