Laravel check if relation is empty

Jessy picture Jessy · Jul 17, 2018 · Viewed 26.9k times · Source

I have an object with some relationships and I need to check if these relations are empty or not, I'm trying to check with is_null, isset, != undefined, etc but nothing works, here is the relationship I get when it's empty :

object(Illuminate\Database\Eloquent\Collection)#197 (1) {
  ["items":protected]=>
    array(0) {
  }
}

Is there a way to check this easily ? Thanks.

Answer

Devon picture Devon · Jul 17, 2018

There are a variety of ways to do this.

In the query itself, you can filter models that do not have any related items:

Model::has('relation')->get()

Once you have a model, if you already have loaded the collection, you can check the count of the collection:

$model->relation->count();

If you want to check without loading the relation, you can run a query on the relation:

$model->relation()->exists()

Note: Replace relation with the name of your relationship in the above examples.