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

mastermarco's avatar

Where on foreign table in belongsToMany relation?

Every of my users can have more "games", I handle it over belongsToMany relation and the connection is saved in "middle table" 'game_users', model: GameUser.

Now I added field "locked"

User.php

public function games(){
    return $this->belongsToMany(Game::class);
}

how can I add condition with model GameUser in this relation games()? Where GameUser locked = 0?

0 likes
2 replies
manelgavalda's avatar

You can use normal where clausules:

public function games(){
    return $this->belongsToMany(Game::class)->where('locked', 0);
}
Cobs's avatar

in a many to many relationship, you can reach the pivot table with wherePivot

return $this->belongsToMany(Game::class, 'game_users', 'user_id', 'game_id')->wherePivot('locked', 0);

have a look to the doc about many to many relationships. it provides many details about how to use and customize intermediate table models with eloquent. https://laravel.com/docs/5.7/eloquent-relationships#many-to-many

Please or to participate in this conversation.