Search code examples
phplaraveleloquentmany-to-many

Get single column from many-to-many relationship in laravel


I created many-to-many relationship between User model and Role model with the pivot table 'role_user'. I want to retrive a single column 'role_name' for the authenticated user as an array.

Here's my configuration for User and Role model:

User.php:

public function roles()
{
    return $this->belongsToMany(Role::class);
}

Role.php:

public function users()
{
    return $this->belongsToMany(User::class);
}

AuthController.php:

public function details()
{
    $user = Auth::user();
    $user['role'] = $user->roles;
    return response()->json(['success' => $user], 20);
}

To which laravel responds with the following:

{"user":{"id":4,"first_name":"Jill","last_name":"mclane","email":"[email protected]","role":[{"id":1,"role_name":"vendor","pivot":{"user_id":4,"role_id":1}}]}}

I want to get role_name column as an array for a selected user. eg. role:['vendor','admin']. I used select method but it returns pivot along with other columns:

$user['role'] = $user->roles()->select('role_name')->get();
//returns {"user":{"id":4,"first_name":"Jill","last_name":"mclane","email":"[email protected]","role":[{"role_name":"vendor","pivot":{"user_id":4,"role_id":1}}]}}

Solution

  • You can use the pluck method on the Collection to do this:

    $user['role'] = $user->roles->pluck('name');
    

    You have loaded the roles relationship when accessing $user->roles though. Though it is not showing in your current output.

    This method also exists for Query Builder.

    $user['role'] = $user->roles()->pluck('name');
    

    This would not load the relationship.

    Laravel 7.x Docs - Collections - Available Methods pluck

    Laravel 7.x Docs - Queries - Retrieving Results - Retrieving A List Of Column Values pluck