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.
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
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community