Is it possible to enable a global scope based on if a middleware is applied or not?
I have a global scope I would like to enable for a certain part of my site and disable on the rest (customer vs admin area) and I'm thinking if you can do this by checking if a middleware "EnableGlobalScopeMiddleware" has run or not?
Yes, create the middleware EnableGlobalScopeMiddleware
php artisan make:middleware EnableGlobalScopeMiddleware
and apply the global scope to the model(s) in the handle
function
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Database\Eloquent\Model;
class EnableGlobalScopeMiddleware
{
public function handle($request, Closure $next)
{
Model::addGlobalScope('foo', function (Builder $builder) {
$builder->where('foo', 'bar');
});
return $next($request);
}
}
Register the middleware in App\Http\Kernel
by adding it to the protected $routeMiddleware
array property
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'global' => \App\Http\Middleware\EnableGlobalScopeMiddleware::class, // <-- Here
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
And apply to it to the specific routes, for example /admin
prefix routes group
Route::middleware(['global'])->prefix('admin')->group(function () {
// Routes here
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With