Reputation: 19
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}}]}}
Upvotes: 1
Views: 2014
Reputation: 50541
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
Upvotes: 4
Reputation: 171
An easy and good way to approach something like this would be to use API resources. That way you can customize the JSON response from the controller.
See: https://laravel.com/docs/7.x/eloquent-resources
Upvotes: 0
Reputation: 12401
use first()
function to get single record
$user['role'] = $user->roles()->first()->role_name;
Upvotes: -1