4

When using custom keys Laravel forces us with scoping, for example, I have a route to getting a country and a post

api/countries/{country:slug}/posts/{post:slug}

but I can't get that using slug key because it doesn't have a relation with country, and in this case, I want to handle scope myself and I don't need implicitly scope binding, but I get an error (Call to undefined method App\Country::posts() ). so because of that I cant using this Laravel feature. is there a way to turn the implicitly scope binding off?

4

1 回答 1

0

如果帖子与国家/地区无关,那么将它们嵌套在 URI 中可能没有意义?

但是,尽管如此,要回答您的问题,您需要做以下两件事之一:

  1. 不用设置 {country:slug},只需使用 {country} 然后覆盖getKeyRouteName()Country 和 Post 模型上的函数。
  2. 或者,特别是如果您想在其他地方使用 ID,请使用显式模型绑定。

在路由文件中使用没有自定义键的 slug

class Post
{
    [...]

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

使用显式路由模型绑定

将以下内容添加到 RouteServiceProvider 的 boot() 方法中:

public function boot()
{
    parent::boot();

    Route::bind('post', function ($value) {
        return App\Post::where('slug', $value)->firstOrFail();
    });
}
于 2020-04-07T05:40:32.640 回答