jon3laze
jon3laze

Reputation: 3196

Use collection->get() instead of collection->pluck()

I am using laravel-permission for managing roles and displaying content. Per the docs you can retrieve a users roles by using $roles = $user->roles()->pluck('name'). My problem is that the data returned is ["admin"] rather than just admin. I was reviewing the collections methods and it looked like get('name') would return what I was looking for. When I try to use the following command Auth::user()->roles()->get('name') I get

1/1
ErrorException in BelongsToMany.php line 360:
Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::getSelectColumns() must be of the type array, string given

It seems to me like the get() method is expecting an array however, I'm trying to reference an item in the array. The raw output of Auth::user()->roles()->get() is [{"id":1,"name":"admin","created_at":"2016-03-10 06:24:47","updated_at":"2016-03-10 06:24:47","pivot":{"user_id":1,"role_id":1}}]

I have found a workaround for pulling the correct content, but it is using regex for removing the unwanted characters that are included in the pluck() method.

preg_replace('/\W/i','', Auth::user()->roles()->pluck('name'))

It seems like I'm missing something or approaching using the get() method incorrectly. Any advice is appreciated.

Upvotes: 0

Views: 1331

Answers (2)

Ivanka Todorova
Ivanka Todorova

Reputation: 10219

That's because an user can have many roles, so roles is a collection. If you are 100% sure that a user will have only one role, you can easily do

Auth::user()->roles()->first()->name

That will get the first item of that collection (the role) and then its name.

Upvotes: 1

stratedge
stratedge

Reputation: 2820

I think pluck() will return the value of the given column for each model in the collection, which would explain the array. In your case it looks like the user has only one role, so you get an array with only one item. If the user had multiple roles, you would likely get an array with multiple items in it.

On the other hand, the get() method is used to execute a query against the database after a query is built. The results of the query are what is returned. To return a collection of models with only a single value you will need to pass an array with just the one column you want, but that will just select models, which does not appear to be what you ultimately need.

You can try this instead: $roles = $user->roles()->first()->name

The call to first() will grab the first model in the collection returned by roles(), and then you can grab the name of the role from that model.

I typically throw some error checking around this:

$role = $user->roles()->first();

if (is_null($role)) {
    //Handle what happens if no role comes back
}

$role_name = $role->name;

Upvotes: 1

Related Questions