Assuming you have your relationships defined in your User and Role models..
$users = User::with('roles')->orderBy('created_at', 'desc')->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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"
Assuming you have your relationships defined in your User and Role models..
$users = User::with('roles')->orderBy('created_at', 'desc')->get();
Please or to participate in this conversation.