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

twg_'s avatar
Level 6

Return values on a many-to-many relationship

I have 3 tables: users, user-to-client, and clients.

In my controller I'm calling all of my clients and I want to return all users related to them as well.

Current code look like this:

$clients = Client::all();

Wasn't quite sure how to call my many-to-many relationship to return the users as well.

0 likes
3 replies
twg_'s avatar
Level 6

I guess that my problem. I'm not sure how to setup the protected function in my Clients Controller. Can you help me with this?

wing5wong's avatar
// client.php
public function users() {
    return $this->belongsToMany('App\User');
}

//user.php
public function clients() {
    return $this->belongsToMany('App\Client');
}



// use it
foreach($client->users as $user) {
    // something with each user
}

Please or to participate in this conversation.