laravel - 自定义路由键名称不起作用

标签 laravel

我希望模型绑定(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/

相关文章:

laravel - 防止 Laravel Eloquent 模型上的某些 CRUD 操作

laravel - 重置密码时如何覆盖电子邮件字段?

javascript - 在生成的内容中调用在母版页中创建的 Javascript 变量

php - Laravel 5 Controller 将 JSON 整数作为字符串发送

php - SQL : Merge two rows by some ID and keep values

php - Laravel 在关系数据库中 Eloquent 分页调用

Laravel 5.5,无法处理构造函数上的策略/授权异常

PHPSpec:输出格式的配置

php - 如何获取链接您的图像的网站的 URL?

php - Laravel 在注销时清除整个 session