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

youngswagx's avatar

How to get data from many to many relationship

I have 3 columns "users", "roles" and "role_user", where the user role has 3 columns, admin(1), staff(2), and client(3) if I want to display users according to their roles how am I to go about it

client controller page

public function index(){

        return view('admin.clients.index',[
            'role' => Role::find(3)
        ]);     
}

client.index page

@foreach ( $role as $user )

{{ $role->name }}
{{ $role->email }} @endforeach

0 likes
4 replies
RayC's avatar

You should be calling $user not $role in your foreach, since you have assigned $role to $user. Plus you will have multiple users per role. You're only returning 1 role, no need to loop through the single role, but rather the users attached to that role.

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

Assuming you've called the relationship method users()

1 like

Please or to participate in this conversation.