我希望模型绑定(bind)使用 id
以外的表列检索给定模型时,我会覆盖 getKeyName
在模型类(Service
在这种情况下),但它不工作!
class Service extends Model{
//override
public function getRouteKey() {
return 'key';
}
}
服务表:
id | key(string,unique) | name(string)
我的路线文件:
Route::resource('services', 'ServiceController');
在
ServiceController
:public function show(Service $service) {
return $service;
}
但是当我去
mysiteurl.com/services/vps
它显示了 404 页面。(
mysiteurl.com/services/1
有效,但我不想在 URL 中使用 id 列)Laravel docs
最佳答案
如果您希望 Laravel 将模型绑定(bind)到具有模型 ID 以外的值的路由,您需要覆盖 getRouteKeyName()
像这样的方法:
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
关于laravel - 自定义路由键名称不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42006711/