I have defined a users
table, a roles
table and a user_role
pivot in my database. The model for the user
is as follows:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
//... Fields defined here
public function roles()
{
return $this->belongsToMany(Role::class, 'user_role');
}
}
Inside the role model, I have this also:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
//... Fields defined here
public function users()
{
return $this->belongsToMany(User::class, 'user_role');
}
}
Now here lies the problem.
When I run the following in the API routes (relatively crude)
$user_roles = \App\Models\User::with('roles')->get();
I get a list of all the users, with each array having an internal array of all the roles. I will like the results such that each user will have one role and if there are multiple roles, I duplicate the user with this new role.
How is this achieved? Thanks in advance for the assistance
My Answer:
php
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class, 'user_role');
}
}
php
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class, 'user_role');
}
}
php
class UserRole extends Model
{
protected $table = 'user_role';
}
php
$users = User::with('roles')->get();
foreach ($users as $user) {
$userRoles = $user->roles->pluck('name')->implode(', ');
echo "User: {$user->name} - Roles: {$userRoles}\n";
}
Rate this post
5 of 5 based on 6736 votesComments