Joyal James
Silkcoder

Silkcoder

What is global scope and how to use global scope in Laravel framework

What is global scope and how to use global scope in Laravel framework

Introduction to Laravel global scope

Joyal James's photo
Joyal James
·Dec 10, 2021·

2 min read

A model in Laravel framework is a PHP class and the methods in this class help us to fetch database records efficiently and quickly.

When a global scope is added to a model, the defined query constraints in the global scope get applied to all executed queries, so global scope allows us to modify all queries without specifying the constraints in each query.

For example, suppose you have a 'users' table in your database with column name 'status' and whenever you fetch data from the users table you want to add a condition 'where status = 1', you can add the following global scope to the User model.

<?php

namespace App\Models;

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

class User extends Model
{
    //define global scope in the booted() method of the Model
    protected static function booted()
    {
        static::addGlobalScope('active', function (Builder $builder) {
            $builder->where('status', '=', '1');
        });
    }
}

All the data fetched through User model will have an extra condition ' where status = '1' '. For example, you can fetch all users using the following code

$allUsers = User::all();

Since you have added the global scope, the executed SQL query will be

select * from users where `status` = '1'

It is possible to add the scope in an external file as follows. Create a new file ActiveScope.php at App/Scopes folder with the following code.

<?php

namespace App\Scopes;

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

class ActiveScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('status', '=', '1');
    }
}

The external scope can be applied to a model in the following way

<?php

namespace App\Models;

use App\Scopes\ActiveScope ; //include the external scope file
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected static function booted()
    {
        static::addGlobalScope(new ActiveScope);
    }
}

Removing Global Scopes

Suppose you may need to fetch a record without the global scope. You can remove a global scope by using the method withoutGlobalScope as follows

User::withoutGlobalScope('active')->get();

If you have scope in a separate class file, then you can use the following code to exclude scope from the query

User::withoutGlobalScope(AncientScope::class)->get()

If you defined multiple scopes and you want to remove only a few then you can use the following code to exclude specific scopes from the query

User::withoutGlobalScopes([
    FirstScope::class, SecondScope::class
])->get();
 
Share this