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

Randy_Johnson's avatar

DB How to get data from a collection relationship

        $data = User::with('roles')->get();

        return view('dashboard.show-users')->with('data', $data);
                        @foreach($data as $datum)
                        <tr>
                            <td>{{$datum->name}}</td>
                            <td>{{$datum->email}}</td>
                            <td>{{$datum->roles['id']}}</td>
                            <td>{{$datum->updated_at}}</td>
                            <td>

I am having trouble accessing the roles name.

0 likes
2 replies
tykus's avatar

The roles is relationship is hasMany, correct? In that case, you would need to pluck the id from the roles Collection on each User instance, and then to echo the list, implode with a comma separator:

@foreach($data as $datum)
<tr>
	// ...
	<td>{{ $datum->roles->pluck('id')->implode(', ') }}</td>
	// ...

More generally, you would need a nested loop to iterate over the relation Collection to output properties of the relation instances.

Aside, why name the variables $data and $datum, and not $users and $user?

IlijaTatalovic's avatar

If a user hasMany Roles, you need another foreach loop for his roles names.


@foreach($user->roles as $role)
	{{ $role->name }} 
@endforeach


Please or to participate in this conversation.