Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TimiAde's avatar

Scoped bindings and without scope bindings

I didnt really understand this aspect in the documentation. can anyone explain it to me scoped bindings and without scoped bindings.

Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
    return $post;
})->scopeBindings();
0 likes
2 replies
LaryAI's avatar
Level 58

Scoped bindings and without scoped bindings are two different ways of injecting route model bindings in Laravel.

When you define a route with model bindings, Laravel will automatically resolve the route parameters by querying the corresponding models from the database. By default, Laravel uses "without scoped bindings" behavior, which means it will resolve the route parameters based on the primary key of the model.

In the example you provided, the route is defined as follows:

Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
    return $post;
})->scopeBindings();

The scopeBindings method is used to enable scoped bindings. Scoped bindings allow you to define custom query constraints when resolving the route parameters. This can be useful when you want to add additional conditions to the query.

To use scoped bindings, you need to define a resolveRouteBinding method on your model. This method will be responsible for resolving the model instance based on the route parameter.

Here's an example of how you can define the resolveRouteBinding method on the Post model:

class Post extends Model
{
    // ...

    public function resolveRouteBinding($value, $field = null)
    {
        return $this->where('slug', $value)->firstOrFail();
    }
}

In this example, the resolveRouteBinding method is defined to resolve the Post model based on the slug column instead of the primary key. This allows you to retrieve the post based on the slug value in the URL.

By using ->scopeBindings(), Laravel will call the resolveRouteBinding method on the Post model to resolve the $post route parameter.

I hope this explanation helps you understand scoped bindings and without scoped bindings in Laravel. Let me know if you have any further questions!

tisuchi's avatar
tisuchi
Best Answer
Level 70

@timiade "Scoped bindings" in Laravel limit data retrieval to a specific context, for instance, getting posts that belong to a particular user. With ->scopeBindings(), Laravel only finds a Post that is related to the provided User, otherwise, it returns a 404 error.

Without scoped bindings (without ->scopeBindings()), Laravel will fetch a Post based on its ID across all posts, regardless of the user it's related to. It broadens the search to the entire dataset, ignoring the user-post relationship.

2 likes

Please or to participate in this conversation.