Laravel Slugable 路由模型绑定奇怪的行为

Laravel Slugable Route Model Binding weird behaviour

我的项目中有一个部分包含最新的新闻文章。为此,我有一个:

  1. Post 型号
  2. Post 资源控制器和一个
  3. 资源Post路线。

Post型号

class Post extends Model
{
    use HasFactory, Sluggable;

    protected $fillable = [...,...];

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

    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'title'
            ]
        ];
    }
}

PostController.php

public function show(Post $post)
{
    dd($post);
}

web.php

Route::resource('/posts', App\Http\Controllers\PostController::class)->only(['index','show']);

索引 (http://localhost/news) 和显示 (http://localhost/news/{slug}) 按预期工作!

现在 problem/bug 我注意到了:

当我将路由从 posts 更改为 news 时,show 方法不再有效。 索引仍然有效。

修改帖子到新闻的路径

Route::resource('/news', App\Http\Controllers\PostController::class)->only(['index','show']); 

http://localhost/news 有效,但 http://localhost/news/{slug} 只显示 Post 模型结构。

你知道这个问题吗?我需要做什么才能解决这个问题?我使用 Laravel 8 和 "cviebrock/eloquent-sluggable": "^8.0" package 作为 slug。感谢您的宝贵时间!

好的。我想通了。我在这里为可能遇到与我相同问题的任何人写下答案。首先。这不是错误。如果你调整路由使得模型名称不再包含在路由中,那么你必须显式绑定路由。 https://laravel.com/docs/8.x/routing#explicit-binding

所有你需要做的。在RouteServiceProvider.php的boot()方法中,添加需要的路由,并与需要的类进行绑定。就我而言,这是新闻而不是 post.

public function boot()
{
    ....
    Route::model('news', \App\Models\Post::class);
}