首页 > 解决方案 > 使用 has Role 返回特定数据

问题描述

我的代码在这里工作正常,但是虽然他在返回中返回用户角色,但我可以阻止用户角色返回它属于使用用户表中的 role_id 的关系

$paths = Path::with(['user','tags'])->where('category_id',1)->get();

foreach($paths as $path){

    if($path->user->hasRole('admin')){
        $AdminPaths [] = $path;
        }
    if($path->user->hasRole('user')){
        $UserPaths [] = $path;
        }
}

return  $UserPaths;

我的用户模型

class User extends \TCG\Voyager\Models\User
 {
use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password', 'username'
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'email_verified_at' => 'datetime',
]; 

}

标签: phplaraveleloquent

解决方案


hasRole从这里调用函数: https ://github.com/the-control-group/voyager/blob/1.2/src/Traits/VoyagerUser.php

它执行loadRolesRelations()加载角色关系,这就是用户加载角色关系的原因。

您可以在检查角色后取消设置角色关系,例如:

foreach($paths as $path){

    if($path->user->hasRole('admin')){
        $AdminPaths [] = $path;
    }
    if($path->user->hasRole('user')){
        $UserPaths [] = $path;
    }
    unset($path->user->role);
}

推荐阅读