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

Kunzilla's avatar

Relationship between three Tables

Hi, i habe three tables for a club signup.

users id, name

clubs id, name

clubs_users id, club_id, user_id

Now i want to get all users that are in the club. I want to get them with this code:

$users = User::with('clubs')->get();

I tried out everything and i stuck. I dont want to use the ->join stuff if possible.

Hope you can help.

0 likes
5 replies
abusalameh's avatar

@Kunzilla you need to define the relationships between the User and Club Models

// this file for User Model 
<?php


use App\Club;

class User Extends Eloquent {



public function clubs() {

return this->belongsToMany(Club::class,'user_id');

}

}

<?php
// This File for Club Model 

use App\User;

class Club Extends Eloquent {



public function users() {

return this->belongsToMany(User::class,'club_id');

}

}

after that you can use it

$users = User::with('clubs')->get();



Kunzilla's avatar

@abusalameh Thanks for your example. I goes in the right direction, but whats with the clubs_users table? This table are for the link betweet "users" and "clubs".

Edit: A user "can" more then one club joined!

Kunzilla's avatar

I got it!

// Club Model

public function users()
    {
        return $this->belongsToMany(User::class, 'clubs_users');
    }

My last question about this. Why must the second argument the table name and not ClubUser::class?

Kunzilla's avatar
public function show(Club $club)
    {

        return view('clubs.show', compact('club'));
    }

Now that controller method shows me every user in the club, without telling eloquent "User::with('clubs')" Is that normal?

Please or to participate in this conversation.