Laravel 7/6 Eloquent Global Scope Tutorial Example

10-Apr-2023

.

Admin

Laravel 7/6  Eloquent Global Scope Tutorial Example

Hi Dev,

Today, I will learn you how to create globle scope in laravel 7/6. I will guide you to create custom query function in model eloquent using globle scope in laravel 7/6.

We can easily use globle query scope in laravel 7/6 application. Many table in same column and same condition to get record then you can use global scope admin side and userside.

If you create laravel model eloquent scope then you don't have to write same logic with where condition again and again.

Sometime, we are working model query like get records, get active records, get banned users etc. At this time you will use globle scope. Here i will give you simple eample of globle scope and it will get active records. So let's see this example here:

Create Global Scope file


app\Scopes\ActiveScope.php

<?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 Scope in User Model

app\User.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use App\Scopes\ActiveScope;

class User extends Model

{

protected $fillable = [

'name','email','password','is_active',

];

protected static function boot()

{

parent::boot();

static::addGlobalScope(new ActiveScope);

}

}

Define Scope in Admin Model

app\Admin.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use App\Scopes\ActiveScope;

class Admin extends Model

{

protected $fillable = [

'name','email','password','is_active',

];

protected static function boot()

{

parent::boot();

static::addGlobalScope(new ActiveScope);

}

}

Get Active Records:

Now you can see how you can use that with your controller file.

You will get only active records using bellow queries:

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

$admins = Admin::select('*')->get();

Get All Records:

You will get only add records using bellow queries from users and admins table:

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

$admins = Admin::select('*')->withoutGlobalScope(ActiveScope::class)->get();

It will help you...

#Laravel 7

#Laravel

#Laravel 6