Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if a Model exists in a many-to-many relationship

I have some data being posted to the server and am retrieving a Player based on that data (an id). I am using the following code:

$player = Player::findOrFail($player_data['id']);

However, I want to check that this Player belongs to a specific Team - a belongsToMany relationship.

Is there a better way than something like:

if (! count($player->team()->find($teamId))) {
    // exit early, form may have been 'hacked'
    abort(404);
}

?

team() and not teams(), even though its a many-to-many.

like image 341
AshMenhennett Avatar asked Feb 04 '26 06:02

AshMenhennett


1 Answers

Use contains() method:

$player->team->contains($teamId);

The contains method determines whether the collection contains a given item

like image 70
Alexey Mezenin Avatar answered Feb 05 '26 22:02

Alexey Mezenin