Laravel中如何基于spatie权限创建仅返回对应角色用户的模型?
实现仅返回对应角色用户的模型
核心思路
利用Eloquent的全局作用域,给模型自动添加角色筛选条件,这样每次执行Student::get()这类查询时,都会自动过滤出拥有对应角色的用户,无需手动重复添加条件。
Student模型实现代码
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Spatie\Permission\Traits\HasRoles; class Student extends Model { use HasRoles; // 引入Spatie权限包的角色处理Trait protected $table = 'users'; protected static function boot() { parent::boot(); // 注册全局作用域,自动筛选拥有student角色的用户 static::addGlobalScope('student_role', function ($query) { // 方式1:使用Spatie包提供的快捷方法,简洁直观 $query->whereRole('student'); // 方式2:原生Eloquent关联查询写法(效果完全一致) // $query->whereHas('roles', function ($subQuery) { // $subQuery->where('name', 'student'); // }); }); } }
Admin/Teacher模型复用
直接复制Student模型的代码,修改类名和全局作用域内的角色名称即可:
// Admin模型示例 class Admin extends Model { use HasRoles; protected $table = 'users'; protected static function boot() { parent::boot(); static::addGlobalScope('admin_role', function ($query) { $query->whereRole('admin'); }); } }
临时取消全局作用域
如果需要偶尔绕过角色限制查询所有用户,可以使用withoutGlobalScope方法:
// 临时获取所有用户,忽略Student模型的角色筛选 Student::withoutGlobalScope('student_role')->get();
内容的提问来源于stack exchange,提问作者Isaac Toyin
相关产品推荐
相关产品推荐

