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

luntik4344's avatar

Many-to-Many relation not working properly

I have three tables: Tournaments, Participants, Users. The structure is:

Tournaments:

    -Id
    -Description
    -Date

Participants

    -Id
    -Id_tourn
    -Id_user

Users

    -Id
    -Name

On my blade template I need all the info from Tournaments table and info of the User which is the participant of that tournament.

I've created the relation between Tournaments and User Models.

UPDATE: Tournaments Model:

    public function users() {
       return $this->belongsToMany('App\User', 'Participants', 'Id_tourn', 'Id_user');
    }

    public function getTournaments()
    {
        return $this->with('users')->get();
    }

Tournament Controller:

    public function show()
    {
        $tourns = new Tournaments();

        $tournaments = $tourns->getTournaments();
        return $tournaments;
    }

but when I try $tournament->users in foreach loop it returns 0 results

Thanks a lot!

0 likes
3 replies
purposemedia's avatar

You a just creating an instance of a class, not getting not a tournament model;

Tournaments::with('users')->all()->each(function($tournament){
    dump($tournment->users);
});

||

Tournaments::with('users')->findOrFail($tounamentId)->users->each(function($user){
    dump($user);
});
luntik4344's avatar
luntik4344
OP
Best Answer
Level 1

Finally, I've found the solution. The problem was that the primary key of my Tournaments Model was set incorrectly. After adding protected $primaryKey = 'Id'; in Tournaments Model, everything started working:)

Please or to participate in this conversation.