Laravel Spatie 获取用户角色
Laravel Spatie To Get User Role
模型文件
class BanUser extends Model
{
public function user()
{
return $this->belongsTo(User::class, "user_id", "id");
}
public static function getBanList()
{
$getlist = BanUser::with(['user'])
->get()
->toArray();
return $getlist;
}
}
//数据
[0] => Array
(
[id] => 3
[user_id] => 2
[created_at] => 2020-09-16T16:06:54.000000Z
[updated_at] => 2020-09-16T16:06:54.000000Z
[user] => Array
(
[id] => 2
[name] => hi
[email] => hi@gmail.com
[email_verified_at] =>
[created_at] => 2020-09-10T12:18:18.000000Z
[updated_at] => 2020-09-10T12:19:11.000000Z
)
)
上面的代码是获取所有ban用户列表,但是每个用户都绑定了一个角色,如何加入角色table才能让每个用户都获取到角色?我使用了 laravel spatie 权限。任何人都可以帮忙吗? :(
我想你可以用这个
public function user()
{
return $this->belongsTo(User::class, "user_id", "id")->with('roles');
}
此 roles
由 laravel spatie
添加,因此您可以使用此
这是角色模型https://github.com/spatie/laravel-permission/blob/master/src/Models/Role.php
您可以使用的所有可用功能
https://github.com/spatie/laravel-permission/blob/master/src/Traits/HasRoles.php
另一种方式
public static function getBanList()
{
$getlist = BanUser::with(['user.roles']) // it will get user as well as all the roles of that user
->get()
->toArray();
return $getlist;
}
你可以像这样弹奏 id
和 name
$request->user()->roles()->pluck('name','id');
模型文件
class BanUser extends Model
{
public function user()
{
return $this->belongsTo(User::class, "user_id", "id");
}
public static function getBanList()
{
$getlist = BanUser::with(['user'])
->get()
->toArray();
return $getlist;
}
}
//数据
[0] => Array
(
[id] => 3
[user_id] => 2
[created_at] => 2020-09-16T16:06:54.000000Z
[updated_at] => 2020-09-16T16:06:54.000000Z
[user] => Array
(
[id] => 2
[name] => hi
[email] => hi@gmail.com
[email_verified_at] =>
[created_at] => 2020-09-10T12:18:18.000000Z
[updated_at] => 2020-09-10T12:19:11.000000Z
)
)
上面的代码是获取所有ban用户列表,但是每个用户都绑定了一个角色,如何加入角色table才能让每个用户都获取到角色?我使用了 laravel spatie 权限。任何人都可以帮忙吗? :(
我想你可以用这个
public function user()
{
return $this->belongsTo(User::class, "user_id", "id")->with('roles');
}
此 roles
由 laravel spatie
添加,因此您可以使用此
这是角色模型https://github.com/spatie/laravel-permission/blob/master/src/Models/Role.php
您可以使用的所有可用功能 https://github.com/spatie/laravel-permission/blob/master/src/Traits/HasRoles.php
另一种方式
public static function getBanList()
{
$getlist = BanUser::with(['user.roles']) // it will get user as well as all the roles of that user
->get()
->toArray();
return $getlist;
}
你可以像这样弹奏 id
和 name
$request->user()->roles()->pluck('name','id');