Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 394
Spialdor Avatar asked Jul 17 '18 13:07

Spialdor


People also ask

What is the use of whereHas in laravel?

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Does laravel have relationship?

Solution. with() is generally used with eager loading, which is a quick way to pull related models. Basically, it means that, along with the main model, Laravel will preload the listed relationship(s). This is beneficial when you need to load additional data and want to avoid making N+1 DB bad practices.


2 Answers

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.

like image 131
Devon Avatar answered Sep 17 '22 06:09

Devon


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() ) {     // ... } 
like image 33
Calos Avatar answered Sep 18 '22 06:09

Calos