Reputation: 24254
I have an instance $person
of Person
and want to check if there is a relation created to a foreign entity (App
).
people: id
people_apps: person_id, app_id
apps: id
The relationships are properly mapped in the Eloquent models. What is the preferred way to check this?
The only way I can think of is something like
$foundApp = $person->apps->filter(function($a) use($searchAppId)
{
return $a->id == $searchAppId;
});
if ($foundApp) {}
but there's probably a better way.
Upvotes: 3
Views: 1867
Reputation: 4111
You can add a custom getter that checks in your model
class Person extends Eloquent {
public function getHasAppWithId($id){
return ($this->apps()->where('id', $id)->count() > 0);
}
}
In your code
$person->hasAppWithId(25);
Upvotes: 2