Sử dụng Global Scope trong Laravel

Trong bài viết này mình sẽ chia sẻ cách định nghĩa global scope trong laravel và cách sử dụng global scope trong ứng dụng laravel 6+. Global scope là một tính năng rất hay trong laravel. Sử dụng Global scope bạn có thể tái sử dụng được những eloquent condition giống nhau trong laravel. Trong

Trong bài viết này mình sẽ chia sẻ cách định nghĩa global scope trong laravel và cách sử dụng global scope trong ứng dụng laravel 6+.
Global scope là một tính năng rất hay trong laravel. Sử dụng Global scope bạn có thể tái sử dụng được những eloquent condition giống nhau trong laravel.
Trong ví dụ này mình sẽ tạo ActiveScope để lấy các sữ liệu có trạng thái active từ model và cách sử dụng với nhiều models có scope giống nhau.
Bạn có thể xem ví dụ bên dưới để hiểu hơn về global scope nhé.
Đầu tiên mình sẽ tạo 2 tables users, admins với dữ liệu demo như bên dưới.
Table users:

Table admins:

Tạo Global Scope File

Trong bước này mình sẽ tạo mới ActiveScope global scope class như bên dưới:
appScopesActiveScope.php

<?phpnamespaceAppScopes;useIlluminateDatabaseEloquentBuilder;useIlluminateDatabaseEloquentModel;useIlluminateDatabaseEloquentScope;classActiveScopeimplementsScope{/**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  IlluminateDatabaseEloquentBuilder  $builder
     * @param  IlluminateDatabaseEloquentModel  $model
     * @return void
     */publicfunctionapply(Builder$builder,Model$model){$builder->where('is_active','=',1);}}

Định nghĩa Global Scope trong User Model

app/Models/User.php

<?phpnamespaceAppModels;useIlluminateDatabaseEloquentModel;useAppScopesActiveScope;classUserextendsModel{protected$fillable=['name','email','password','is_active',];protectedstaticfunctionboot(){parent::boot();static::addGlobalScope(newActiveScope);}}

Định nghĩa Global Scope trong Admin Model

app/Models/Admin.php

<?php
  
namespace AppModels;
  
use IlluminateDatabaseEloquentModel;
use AppScopesActiveScope;
  
class Admin extends Model
{
    protected $fillable = [
        'name','email','password','is_active',
    ];
  
    protected static function boot()
    {
        parent::boot();
  
        return static::addGlobalScope(new ActiveScope);
    }
}

Tạo UserController.php

Mình tạo UserController và thêm code như bên dưới.

<?phpnamespaceAppHttpControllers;useIlluminateHttpRequest;useAppModelsUser;useAppModelsAdmin;useAppScopesActiveScope;classUserControllerextendsController{publicfunctionindex(){//write code here}}

Kiểm tra query lấy dữ liệu

Thực hiện lấy tất cả các bản ghi có trạng thái is_active = 1
Thêm đoạn code bên dưới vào hàm index để lấy dữ liệu từ 2 bảng users,admins.

publicfunctionindex(){$users=User::select('*')->get();$admins=Admin::select('*')->get();dd($users,$admins);}

Output dữ liệu bảng users:

array:1 [▼
  0 => array:7 [▼
    "id" => 2
    "name" => "user2"
    "email" => "[email protected]"
    "email_verified_at" => null
    "is_active" => 1
    "created_at" => null
    "updated_at" => null
  ]
]

Output dữ liệu bảng admins:

array:2 [▼
  0 => array:9 [▼
    "id" => 2
    "name" => "admin2"
    "email" => "[email protected]"
    "email_verified_at" => null
    "password" => ""
    "remember_token" => null
    "is_active" => 1
    "created_at" => null
    "updated_at" => null
  ]
  1 => array:9 [▼
    "id" => 3
    "name" => "admin3"
    "email" => "[email protected]"
    "email_verified_at" => null
    "password" => ""
    "remember_token" => null
    "is_active" => 1
    "created_at" => null
    "updated_at" => null
  ]
]

Thực hiện lấy tất cả các bản ghi không phân bit trạng thái is_active của dữ liệu .

publicfunctionindex(){$users=User::select('*')->withoutGlobalScope(ActiveScope::class)->get()->toArray();$admins=Admin::select('*')->withoutGlobalScope(ActiveScope::class)->get()->toArray();dd($users,$admins);}

Output dữ liệu bảng users:

array:2 [▼
  0 => array:7 [▼
    "id" => 1
    "name" => "user1"
    "email" => "[email protected]"
    "email_verified_at" => null
    "is_active" => 0
    "created_at" => null
    "updated_at" => null
  ]
  1 => array:7 [▼
    "id" => 2
    "name" => "user2"
    "email" => "[email protected]"
    "email_verified_at" => null
    "is_active" => 1
    "created_at" => null
    "updated_at" => null
  ]
]

Output dữ liệu bảng admins:

array:3 [▼
  0 => array:9 [▼
    "id" => 1
    "name" => "admin1"
    "email" => "[email protected]"
    "email_verified_at" => null
    "password" => ""
    "remember_token" => null
    "is_active" => 0
    "created_at" => null
    "updated_at" => null
  ]
  1 => array:9 [▼
    "id" => 2
    "name" => "admin2"
    "email" => "[email protected]"
    "email_verified_at" => null
    "password" => ""
    "remember_token" => null
    "is_active" => 1
    "created_at" => null
    "updated_at" => null
  ]
  2 => array:9 [▼
    "id" => 3
    "name" => "admin3"
    "email" => "[email protected]"
    "email_verified_at" => null
    "password" => ""
    "remember_token" => null
    "is_active" => 1
    "created_at" => null
    "updated_at" => null
  ]
]

Mình hy vọng bài viết sẽ giúp ích cho các bạn!
Tham khảo: https://www.itsolutionstuff.com/

Nguồn: viblo.asia

Bài viết liên quan

7 Cách Tăng Tốc Ứng Dụng React Hiệu Quả Mà Bạn Có Thể Làm Ngay

React là một thư viện JavaScript phổ biến trong việc xây dựng giao diện người d

Trung Quốc “thả quân bài tẩy”: hàng loạt robot hình người!

MỘT CUỘC CÁCH MẠNG ROBOT ĐANG HÌNH THÀNH Ở TRUNG QUỐC Thượng Hải, ngày 13/5 –

9 Mẹo lập trình Web “ẩn mình” giúp tiết kiệm hàng giờ đồng hồ

Hầu hết các lập trình viên (kể cả những người giỏi) đều tốn thời gian x

Can GPT-4o Generate Images? All You Need to Know about GPT-4o-image

OpenAI‘s GPT-4o, introduced on March 25, 2025, has revolutionized the way we create visual con