38

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.

Spialdor
  • 1,475
  • 5
  • 20
  • 46

7 Answers7

80

There are a variety of ways to do this.

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

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

#2 Once you have a model, if you already have loaded the collection (which below #4 checks), you can call the count() method of the collection:

$model->posts->count();

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

$model->posts()->exists()

#4 If you want to check if the collection was eager loaded or not:

if ($model->relationLoaded('posts')) {
    // Use the collection, like #2 does...
}

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

Top-Master
  • 7,611
  • 5
  • 39
  • 71
Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
22

If model already have loaded relationship, you can determine the variable is null or call isEmpty() to check related items:

// For one relation:
if ( $model->relation ) {
    // ...
} else {
    // $model->relation is null
}

// For many relations:
if ( $model->relation->isEmpty() ) {
    // ...
}
Calos
  • 1,783
  • 19
  • 28
10

First, you might want to check if your Relation is loaded

if ($user->relationLoaded('posts'))...

second, when it is loaded, you might want to see if it is an empty Collection or Null,

if ($user->posts()->exists())...

PS

use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\Collection;
Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
3
Model::has('relation')->get();
Model::doesntHave('relation')->get();
Imad Ullah
  • 929
  • 9
  • 17
1
    $model->relation()->exists()
if (count($model->relation))
{
  // check exists
}

also 2nd method

if(!is_null($model->relation)) {
   ....
}
pardeep
  • 359
  • 1
  • 5
  • 7
  • I already try the second method with my relation (is_null($experiment->tm())) but this doesn't work too :/ and the first one returns me nothing :/ – Spialdor Jul 17 '18 at 13:32
1

This doesn't directly answer the question, but you can use Laravel's optional helper to call methods on a relationship you suspect might not have a value:

optional($user->comments)->where('is_popular', true);

If the user doesn't have comments, this will return null. Otherwise it will return the user's popular comments.

Patrick.SE
  • 4,444
  • 5
  • 34
  • 44
1

If the relation is not always empty, way more clear way is to use Laravel build-in helper 'optional'

For example, this code will not throw an error if the relation is null

  {{ optional($this->category)->name }}
Martin Tonev
  • 747
  • 12
  • 21