DEV Community

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

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay