使用具有角色返回特定数据

时间:2019-04-11 08:43:19

标签: php laravel eloquent

我的代码在这里工作正常,但是尽管他正在返回用户角色,但是我可以防止用户角色返回它吗?它属于使用用户表中的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',
]; 

}

1 个答案:

答案 0 :(得分:1)

您要从此处调用函数hasRolehttps://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);
}