Check if there is a relationship with a foreign property in Laravel / Eloquent

I have an instance of $personof Personand you want to check if the relation created for the external object ( App) exists .

people: id
people_apps: person_id, app_id
apps: id

Relationships are displayed correctly in Eloquent models. What is the preferred way to test 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 probably the best way.

+3
source share
1 answer

You can add a custom getter that validates your model

class Person extends Eloquent {

  public function getHasAppWithId($id){
    return ($this->apps()->where('id', $id)->count() > 0);
  }

}

In your code

$person->hasAppWithId(25);
+2
source

All Articles