Laravel Eloquent Global Scope Example Tutorial

In this quick example i will discuss about laravel global scope. Laravel global scopes allow us to add constraints to all queries for a given model. You know that Laravel's own soft delete functionality utilizes global scopes to only pull "non-deleted" models from the database.

If you want so give some constraint in your query globaly then your own global scopes can provide a convenient, easy way to make sure every query for a given model receives certain constraints. 

How we can define that global scope ? Writing a global scope is very simple. Define a class that implements the Illuminate\Database\Eloquent\Scope interface. This interface requires you to implement one method: apply. The apply method may add where constraints to the query as needed:

See the below example to understand laravel global scope and how to use it.

Create Global Scope 

In this step, we will create new ActiveScope global scope class as like bellow:

app\Scopes\ActiveScope.php

  
namespace App\Scopes;
  
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
  
class ActiveScope 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->where('is_active', '=', 1);
    }
}

 

Define Global Scope For a Model

Here, we will add scope in our user model. So when we query in controller then we will use that scope in laravel model.

app/User.php

namespace App;
  
use Illuminate\Database\Eloquent\Model;
use App\Scopes\ActiveScope;
  
class User extends Model
{
    protected static function boot()
    {
        parent::boot();
  
        static::addGlobalScope(new ActiveScope);
    }
}

 

After adding the scope, a query to User::all() will produce the following SQL:

OUTPUT
select * from `users` where `is_active` = 1

 

Recommended : Laravel 7.x Eloquent Model Query Scope Example

 

You can also use this query to avoid global scope.

$users = User::select('*')->withoutGlobalScope(ActiveScope::class)->get();

 

Anonymous Global Scopes Laravel

Eloquent also allows you to define global scopes using Closures, which is particularly useful for simple scopes that do not warrant a separate class:

namespace App\Models;

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

class User extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::addGlobalScope('age', function (Builder $builder) {
            $builder->where('age', '>', 200);
        });
    }
}

 

Hope it can help you.