How to use custom keys in laravel routes without scoping?

Viewed 673

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?

1 Answers

If the posts are not related to the countries, it may not make sense to nest them in the URI?

But, nonetheless, to answer your question, you need to do one of two things:

  1. Instead of setting {country:slug}, just use {country} and then override getKeyRouteName() function on your Country and Post models.
  2. Alternatively, especially if you want to use the ID elsewhere, use explicit model binding.

To use a slug without custom keys in the routes file

class Post
{
    [...]

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

To use explicit route model binding

Add the following to the boot() method of your RouteServiceProvider:

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

    Route::bind('post', function ($value) {
        return App\Post::where('slug', $value)->firstOrFail();
    });
}
Related