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

chaudigv's avatar

Route model binding with scopes

Just like deleted_at is applied to all eloquent queries, is there way to apply a global scope on few selected routes?

e.g. Adding a scope on all the show routes.

Possible solution (I think): Create a middleware. Add the middleware attribute on selected routes. But how would the middleware know to bind a scope unto eloquent?

0 likes
6 replies
chaudigv's avatar

Just so it's clear to me. I should Naming Resource Route Parameters on the selected routes and use Customizing The Resolution Logic to bind the scope conditions. Is that what you meant?

MichalOravec's avatar

@chaudigv Naming Resource Route Parameters will work for entirety resource controller.

so better will be to exclude that route from resource controller

Route::get('users/{custom_user}', [UserController::class, 'show']);

Route::resource('users', UserController::class)->except([
    'show'
]);

Definition of custom_user could be something like this

use App\Models\User;
use Illuminate\Support\Facades\Route;

/**
 * Define your route model bindings, pattern filters, etc.
 *
 * @return void
 */
public function boot()
{
    Route::bind('custom_user', function ($value) {
        return User::localScope()->findOrFail($value);
    });

    // ...
}
tykus's avatar

You could make a binding for a specific wildcard in the route URI, and use a local scope rather than a global scope; for example:

Route::bind('scopedUser', fn ($value) => User::localScope()->findOrFail($value));
Route::get('users/{scopedUser}', fn (User $scopedUser) => dump($scopedUser));

This allows you to also define routes with the generic {user} wildcard, which will not use the resolution logic above.

chaudigv's avatar

True. In such case, i have to add local scopes to respective models. And rename the model binding parameter on respective controllers. That is still a bit of work.

Is there no possibility of using middleware with route binding and global scopes? This way I simply have to add conditions on selected routes, rather than making changes at bunch of places.

tykus's avatar

i have to add local scopes to respective models

Is the global scope shared (e.g. in a Trait) amongst a number of Models currently? You could easily convert it to a localScope.

Please or to participate in this conversation.