Spialdor
Spialdor

Reputation: 1645

Laravel check if relation is empty

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.

Upvotes: 41

Views: 83094

Answers (7)

Martin Tonev
Martin Tonev

Reputation: 775

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 }}

Upvotes: 1

Devon Bessemer
Devon Bessemer

Reputation: 35337

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.

Upvotes: 84

Imad Ullah
Imad Ullah

Reputation: 1218

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

Upvotes: 6

Yevgeniy Afanasyev
Yevgeniy Afanasyev

Reputation: 41320

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;

Upvotes: 11

Patrick.SE
Patrick.SE

Reputation: 4564

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.

Upvotes: 1

Calos
Calos

Reputation: 1942

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() ) {
    // ...
}

Upvotes: 24

pardeep
pardeep

Reputation: 359

    $model->relation()->exists()
if (count($model->relation))
{
  // check exists
}

also 2nd method

if(!is_null($model->relation)) {
   ....
}

Upvotes: 1

Related Questions