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

非 Y 不嫁゛ 提交于 2019-12-24 09:24:11

问题


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.


回答1:


Use contains() method:

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

The contains method determines whether the collection contains a given item



来源:https://stackoverflow.com/questions/41713730/best-way-to-check-if-a-model-exists-in-a-many-to-many-relationship

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!