Laravel Global Scope Tutorial Example (ok)

https://www.itsolutionstuff.com/post/laravel-global-scope-tutorial-exampleexample.html

C:\xampp\htdocs\reset\routes\web.php

<?php
use Illuminate\Support\Facades\Route;
use App\Models\User;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
    return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('my-components', function () {
  $users = User::select('*')->get();
  return view('welcome')->with(compact('users'));
});

C:\xampp\htdocs\reset\resources\views\welcome.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">

        <!-- Styles -->
        <style>
            /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}a{background-color:transparent}[hidden]{display:none}html{font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;line-height:1.5}*,:after,:before{box-sizing:border-box;border:0 solid #e2e8f0}a{color:inherit;text-decoration:inherit}svg,video{display:block;vertical-align:middle}video{max-width:100%;height:auto}.bg-white{--bg-opacity:1;background-color:#fff;background-color:rgba(255,255,255,var(--bg-opacity))}.bg-gray-100{--bg-opacity:1;background-color:#f7fafc;background-color:rgba(247,250,252,var(--bg-opacity))}.border-gray-200{--border-opacity:1;border-color:#edf2f7;border-color:rgba(237,242,247,var(--border-opacity))}.border-t{border-top-width:1px}.flex{display:flex}.grid{display:grid}.hidden{display:none}.items-center{align-items:center}.justify-center{justify-content:center}.font-semibold{font-weight:600}.h-5{height:1.25rem}.h-8{height:2rem}.h-16{height:4rem}.text-sm{font-size:.875rem}.text-lg{font-size:1.125rem}.leading-7{line-height:1.75rem}.mx-auto{margin-left:auto;margin-right:auto}.ml-1{margin-left:.25rem}.mt-2{margin-top:.5rem}.mr-2{margin-right:.5rem}.ml-2{margin-left:.5rem}.mt-4{margin-top:1rem}.ml-4{margin-left:1rem}.mt-8{margin-top:2rem}.ml-12{margin-left:3rem}.-mt-px{margin-top:-1px}.max-w-6xl{max-width:72rem}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.p-6{padding:1.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.pt-8{padding-top:2rem}.fixed{position:fixed}.relative{position:relative}.top-0{top:0}.right-0{right:0}.shadow{box-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px 0 rgba(0,0,0,.06)}.text-center{text-align:center}.text-gray-200{--text-opacity:1;color:#edf2f7;color:rgba(237,242,247,var(--text-opacity))}.text-gray-300{--text-opacity:1;color:#e2e8f0;color:rgba(226,232,240,var(--text-opacity))}.text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.text-gray-500{--text-opacity:1;color:#a0aec0;color:rgba(160,174,192,var(--text-opacity))}.text-gray-600{--text-opacity:1;color:#718096;color:rgba(113,128,150,var(--text-opacity))}.text-gray-700{--text-opacity:1;color:#4a5568;color:rgba(74,85,104,var(--text-opacity))}.text-gray-900{--text-opacity:1;color:#1a202c;color:rgba(26,32,44,var(--text-opacity))}.underline{text-decoration:underline}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.w-5{width:1.25rem}.w-8{width:2rem}.w-auto{width:auto}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}@media (min-width:640px){.sm\:rounded-lg{border-radius:.5rem}.sm\:block{display:block}.sm\:items-center{align-items:center}.sm\:justify-start{justify-content:flex-start}.sm\:justify-between{justify-content:space-between}.sm\:h-20{height:5rem}.sm\:ml-0{margin-left:0}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:pt-0{padding-top:0}.sm\:text-left{text-align:left}.sm\:text-right{text-align:right}}@media (min-width:768px){.md\:border-t-0{border-top-width:0}.md\:border-l{border-left-width:1px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width:1024px){.lg\:px-8{padding-left:2rem;padding-right:2rem}}@media (prefers-color-scheme:dark){.dark\:bg-gray-800{--bg-opacity:1;background-color:#2d3748;background-color:rgba(45,55,72,var(--bg-opacity))}.dark\:bg-gray-900{--bg-opacity:1;background-color:#1a202c;background-color:rgba(26,32,44,var(--bg-opacity))}.dark\:border-gray-700{--border-opacity:1;border-color:#4a5568;border-color:rgba(74,85,104,var(--border-opacity))}.dark\:text-white{--text-opacity:1;color:#fff;color:rgba(255,255,255,var(--text-opacity))}.dark\:text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.dark\:text-gray-500{--tw-text-opacity:1;color:#6b7280;color:rgba(107,114,128,var(--tw-text-opacity))}}
        </style>
    </head>
    <body class="antialiased">
        <div class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center py-4 sm:pt-0">
            @if (Route::has('login'))
                <div class="hidden fixed top-0 right-0 px-6 py-4 sm:block">
                    @auth
                        <a href="{{ url('/home') }}" class="text-sm text-gray-700 dark:text-gray-500 underline">Home</a>
                    @else
                        <a href="{{ route('login') }}" class="text-sm text-gray-700 dark:text-gray-500 underline">Log in</a>

                        @if (Route::has('register'))
                            <a href="{{ route('register') }}" class="ml-4 text-sm text-gray-700 dark:text-gray-500 underline">Register</a>
                        @endif
                    @endauth
                </div>
            @endif

            <div class="container">
                <div class="row">
                    @foreach ($users as $user)
                        <p>{{ $user->name }}</p>
                    @endforeach
                </div>
            </div>
        </div>
    </body>
</html>

C:\xampp\htdocs\reset\database\migrations\2014_10_12_000000_create_users_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('is_active');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

C:\xampp\htdocs\reset\database\factories\UserFactory.php

<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory {
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'name'              => $this->faker->name(),
      'is_active'         => $this->faker->numberBetween(1, 10),
      'email'             => $this->faker->unique()->safeEmail(),
      'email_verified_at' => now(),
      'password'          => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
      'remember_token'    => Str::random(10),
    ];
  }
  /**
   * Indicate that the model's email address should be unverified.
   *
   * @return \Illuminate\Database\Eloquent\Factories\Factory
   */
  public function unverified() {
    return $this->state(function (array $attributes) {
      return [
        'email_verified_at' => null,
      ];
    });
  }
}

C:\xampp\htdocs\reset\app\Models\User.php

<?php
namespace App\Models;
use App\Scopes\ActiveScope;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable {
  use HasApiTokens, HasFactory, Notifiable;
  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
    'name', 'email', 'password', 'is_active',
  ];
  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];
  /**
   * The attributes that should be cast.
   *
   * @var array<string, string>
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
  protected static function boot() {
    parent::boot();
    static::addGlobalScope(new ActiveScope());
  }
}

C:\xampp\htdocs\reset\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);
  }
}

C:\xampp\htdocs\reset\app\Admin.php

<?php
namespace App;
use App\Scopes\ActiveScope;
use Illuminate\Database\Eloquent\Model;
class Admin extends Model {
  protected $fillable = [
    'name', 'email', 'password', 'is_active',
  ];
  protected static function boot() {
    parent::boot();
    return static::addGlobalScope(new ActiveScope());
  }
}

Sử dụng withoutGlobalScope

C:\xampp\htdocs\reset\routes\web.php

<?php
use Illuminate\Support\Facades\Route;
use App\Models\User;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
    return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('my-components', function () {
  $users = User::select('*')->get();
  // $users = User::withoutGlobalScope('App\Scopes\ActiveScope')->get();
  return view('welcome')->with(compact('users'));
});

Laravel Global Scope Tutorial Example

By Hardik Savani December 28, 2019 Category : LaravelPlayUnmuteLoaded: 1.17%FullscreenVDO.AIHi Guys,

In this tutorial, i would like to show you how to define global scope in laravel and how to use global scope in laravel 6 application. i will give you demo to how to create global scope in laravel and how to remove global scope in laravel 6, laravel 7, laravel 8 and laravel 9.

Global Scope is a very important concept of laravel 6. using Global Scope you can reuse same eloquent condition in laravel application. i also written tutorial of how to create local scope in laravel 6. Local scope it only for single model. But you define global scope then you can use with all model.

If you want to see how works local scope then you can simply read this tutorial: https://www.itsolutionstuff.com/post/how-to-create-and-use-query-scope-in-laravel-eloquentexample.html.

In this example we will create ActiveScope for getting only active records from model. How to use with multiple models same scope. You can check it step by step bellow:

Create Global Scope File

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

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

Here, we will add today scope in our user model. So when we query in controller then we will use that scope in laravel 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 Global Scope in Admin Model

Here, we will add today scope in our admin model. So when we query in controller then we will use that scope in laravel 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();          return 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:

Read Also: How to Create and Use Query Scope in Laravel Eloquent

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

I hope it can help you...

Last updated