Reputation: 4232
How to retrieve a column of intermediate table as an array?
For example:
The intermediate table of users
and roles
,named role_user
,it is like this:
id
user_id
role_id
I want to get current user's role_id
s:
public function test()
{
//$roles is a collection.
$roles=Auth::user()->roles;
//I want to get `role_id`s like this:
//$roleIds=[1,2,3];
}
How to do it?
Upvotes: 0
Views: 452
Reputation: 585
You can try to use Collection's pluck
method. See the documentation.
$roleIds = $roles->pluck('id')
Upvotes: 1
Reputation: 4826
use this eloquent relationship function in your user model
public function roles()
{
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
}
public function getUserRole()
{
return $this->roles()->first();
}
if user has one role you can access like this
Auth::user()->getUserRole();
if user has many roles you can call
Auth::user()->roles;
Upvotes: 1