Support the ongoing development of Laravel.io →
Database Eloquent

Hi,

Ok,so I am setting up a relationship between my users and roles table, everything went fine until I tried to get every record. For example, If I just go with:

User::with('roles')->findOrFail(1);

Then all good, it returns the user and in that instance the 2 roles assigned.

However what I can't wrap my head around us this:

Say I want to get all the users and all their roles so I can display them out in a table for example, how would I do that? I just can't seem to wrap my head around it.

Last updated 3 years ago.
0
$users = User::with('roles')->all();
0

Thanks the full solution I ended up with was this.

User::with('roles')->get();

Then pass that to the view with

return view('admin.users.index')->with('users', $users);

And loop through the results like so:

@foreach ($users as $user)
	<tr>
		<td>{!! $user->id !!}</td>
		<td>{!! $user->name !!}</td>
		<td>{!! $user->email !!}</td>
		<td>{!! $user->created_at !!}</td>
		<td>{!! $user->updated_at !!}</td>
		<td>
		
			@foreach ($user->roles as $role)
			{!! $role->name !!}<br />
			@endforeach
		
		</td>
	</tr>
	@endforeach
0

Sign in to participate in this thread!

Eventy

Your banner here too?

SCC-Lee scc-lee Joined 22 Oct 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.