Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if relation exist with foreign entity in Laravel / Eloquent

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.

like image 753
Znarkus Avatar asked Dec 30 '25 20:12

Znarkus


1 Answers

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);
like image 75
JackPoint Avatar answered Jan 01 '26 16:01

JackPoint