【问题标题】:Customizing Route Key Name not working自定义路由键名称不起作用
【发布时间】:2017-02-02 15:55:32
【问题描述】:

我希望模型绑定在检索给定模型时使用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

【问题讨论】:

  • 您需要将方法重命名为 getRouteKeyName 而不是 getRouteKey
  • 这解决了您的问题吗?

标签: laravel


【解决方案1】:

如果您希望 Laravel 将您的模型绑定到具有模型 ID 以外的值的路由,您需要像这样覆盖 getRouteKeyName() 方法:

/**
 * Get the route key for the model.
 *
 * @return string
 */
public function getRouteKeyName()
{
    return 'slug';
}

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 1970-01-01
    • 2014-01-26
    • 2013-11-04
    • 2020-03-09
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多