【问题标题】:Why Model is not returning the data via slug except id?为什么模型除了 id 不通过 slug 返回数据?
【发布时间】:2020-04-16 09:52:33
【问题描述】:

当我尝试通过 slug 而不是通过 id 获取数据时,我遇到了 laravel 视图的问题。 这是我的路线:

Route::get('post/{post}','PostController@post')->name('post');

这是 postController 函数:

public function post(post $post)
{
    return view('user.post',compact('post'));
}

这是模型函数:

public function grtRouteKeyName()
{
    return 'slug';
}

它得到错误 404,但什么时候对 Route 进行一些更改:

Route::get('post/{slug}','PostController@post')->name('post');

它返回视图,但不返回我想要的表中的数据。

【问题讨论】:

  • 模型函数拼写错误

标签: laravel slug laravel-6


【解决方案1】:

简单介绍 Laravel 的implicit-binding

如果/{post} 包含一个 id 并且您的表有 id 列,那么 Laravel 会处理它。

如果您希望模型绑定在检索给定模型类时使用 id 以外的数据库列,您可以覆盖 Eloquent 模型上的 getRouteKeyName 方法:

public function getRouteKeyName()
{
    return 'slug';  // db column name
}

在上面的问题中,需要把方法名grtRouteKeyName改成getRouteKeyName的拼写,希望可以。

【讨论】:

    【解决方案2】:

    你拼错了getRouteKeyName()

    【讨论】:

    • 是的,后来找到了!谢谢
    【解决方案3】:

    你的函数名不正确,改成这样:

    public function getRouteKeyName() {
        return 'slug';  // table column name.
    }
    

    【讨论】:

    • 知道了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多