Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ricardosoares's avatar

Query

My question is, i have users table, roles table, role_users table, and i want to make the list of all users, and the roles for each user, but doing it obviously is just returning me the id, and now how can i go pickup the name on the roles table? I guess i can do it with join but it's the best way? or there is a better way to do it?

Query on controller

 $users = User::Join('role_users', 'users.id', '=', 'role_users.user_id')
                    ->select('users.*', 'role_users.role_id')
                    ->orderBy('users.created_at', 'desc')
                    ->get();

return view('users.index', compact('users'));

Output:

"id" => "1"
"name" => "Test"
"email" => "[email protected]"
"role_id" => "5"
0 likes
10 replies
willvincent's avatar
Level 54

Assuming you have your relationships defined in your User and Role models..

$users = User::with('roles')->orderBy('created_at', 'desc')->get();
1 like
ricardosoares's avatar

Well im dumbass, when i saw i remembered it, not codding for long time, make this type of things, rip xd

Thanks anyway

ricardosoares's avatar

For example, doing that query the roles relation, returns a collection so in the view i need to foreach the roles to get the name, it means the roles relation isn't set one to one right (im using package)?

The main question is, the way to make roles return array instead a collection is to make one to one relation? or im i wrong?

willvincent's avatar

Not sure what you're hoping to achieve.. how would an array be better than the collection?

ricardosoares's avatar

Because on the view for example with collection i need to foreach the to get the name

willvincent's avatar

And how would you get the name from an array without a loop?

Maybe explain what you're wanting to do?

willvincent's avatar

So you're not talking about the difference between collection and array but rather you're wanting a different kind of relationship altogether.. a 1 to many vs a many to many...

The syntax you're looking for will only work if users only have one role, not the ability to have many roles.

Please or to participate in this conversation.