- vừa được xem lúc

Sử dụng Global Scope trong Laravel

0 0 17

Người đăng: Kumako

Theo Viblo Asia

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:
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); }
}

Định nghĩa Global Scope trong User Model

app/Models/User.php

<?php namespace App\Models; 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); }
}

Định nghĩa Global Scope trong Admin Model

app/Models/Admin.php

<?php namespace App\Models; 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); }
}

Tạo UserController.php

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

<?php namespace App\Http\Controllers; use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Admin;
use App\Scopes\ActiveScope; class UserController extends Controller
{ public function index() { //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.

 public function index() { $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" => "_@.com" "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" => "_@.com" "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" => "_@.com" "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 .

 public function index() { $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" => "_@.com" "email_verified_at" => null "is_active" => 0 "created_at" => null "updated_at" => null ] 1 => array:7 [▼ "id" => 2 "name" => "user2" "email" => "_@.com" "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" => "_@.com" "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" => "_@.com" "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" => "_@.com" "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/

Bình luận

Bài viết tương tự

- vừa được xem lúc

Tìm hiểu về Resource Controller trong Laravel

Giới thiệu. Trong laravel, việc sử dụng các route post, get, group để gọi đến 1 action của Controller đã là quá quen đối với các bạn sử dụng framework này.

0 0 335

- vừa được xem lúc

Phân quyền đơn giản với package Laravel permission

Như các bạn đã biết, phân quyền trong một ứng dụng là một phần không thể thiếu trong việc phát triển phần mềm, dù đó là ứng dụng web hay là mobile. Vậy nên, hôm nay mình sẽ giới thiệu một package có thể giúp các bạn phân quyền nhanh và đơn giản trong một website được viết bằng PHP với framework là L

0 0 421

- vừa được xem lúc

Sử dụng Swagger để xây dựng API documentation

Giới thiệu về Swagger. RESTful API là một tiêu chuẩn dùng trong việc thiết kế API cho các ứng dụng web (thiết kế Web services) để tiện cho việc quản lý các resource.

0 0 1k

- vừa được xem lúc

Ví dụ CRUD với Laravel và Vuejs.

1. Cài đặt Laravel. composer create-project --prefer-dist laravel/laravel vuelaravelcrud. .

0 0 141

- vừa được xem lúc

Một số tips khi dùng laravel (Part 1)

1. Show database query in raw SQL format. DB::enableQueryLog(); // Bật tính năng query logging. DB::table('users')->get(); // Chạy truy vấn bạn muốn ghi log.

0 0 69

- vừa được xem lúc

Inertiajs - Xây dựng Single Page App không cần API

Tiêu đề là mình lấy từ trang chủ của https://inertiajs.com/ chứ không phải mình tự nghĩ ra đâu nhé :v. Lâu lâu rồi chưa động tới Laravel (dự án cuối cùng mình code là ở ver 5.8), thế nên một ngày đẹp trời lượn vào đọc docs ver 8.

0 0 227