Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Add global scope to Models if a certain middleware is run

Tags:

php

laravel

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?

like image 545
Sheph Avatar asked Dec 31 '22 13:12

Sheph


1 Answers

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
});
like image 65
Salim Djerbouh Avatar answered Jan 05 '23 10:01

Salim Djerbouh