DEV Community

Cover image for Global scope in Laravel, the easy way.

Global scope in Laravel, the easy way.

Ever found your self repeating a query for a specific role, as an example.
Lets put a scenario where we actually need a global scope, we have an orders table, there is free orders and payed orders;

  • Clients can see only their orders.
  • Commercials can see orders of their clients.
  • Shipping and back-office can see all the orders.

First thing we create a scope lets call it App\Scopes\OrderScope.php

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Auth;

class ComplaintScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        // builder is the query 
        if (Auth::user()->isClient()) {
            $builder->where('user_id', Auth::id());
        } elseif (Auth::user()->isCommercial()) {
            $builder->whereHas('user', function (Builder $query) {
                $query->where('commercial_id', Auth::user()->id);
            });
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Then we use it in our model like that.

use App\Scopes\ComplaintScope;

//add that function to the model
    protected static function booted()
    {
        static::addGlobalScope(new ComplaintScope);
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)