laravel check if collection contains model laravel check if collection contains model laravel laravel

laravel check if collection contains model


For many-to-many you can use contains() method:

$game = Game::where('title', 'pacman')->first();if ($game->users->contains($userId)) {    // Do something.}


You can use ->user() , so your code would become:

$gameHasUser =  $gameUsers->find(1)->user()

find(1) is just an example for illustration. You can also check Eloquent Loading Relationships Laravel Doc.


You can use where clause to check game existence in the user's game list:

$user = User::find(1);$gameHasUser = $user->games()->where('title', 'pacman')->isNotEmpty();