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

Thay đổi Package Name của Android Studio dể dàng với plugin APR

Nếu bạn đang gặp khó khăn hoặc bế tắc trong việc thay đổi package name trong And

Lỗi không Update Meta_Value Khi thay thế hình ảnh cũ bằng hình ảnh mới trong WordPress

Mã dưới đây hoạt động tốt có 1 lỗi không update được postmeta ” meta_key=

Bài 1 – React Native DevOps các khái niệm và các cài đặt căn bản

Hướng dẫn setup jenkins agent để bắt đầu build mobile bằng jenkins cho devloper an t

Chuyển đổi từ monolith sang microservices qua ví dụ

1. Why microservices? Microservices là kiến trúc hệ thống phần mềm hướng dịch vụ,