zwl1619
zwl1619

Reputation: 4232

Laravel : How to retrieve a column of intermediate table as an array?

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_ids:

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

Answers (2)

tooleks
tooleks

Reputation: 585

You can try to use Collection's pluck method. See the documentation.

$roleIds = $roles->pluck('id')

Upvotes: 1

Hamelraj
Hamelraj

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

Related Questions