Laravel check if relation is empty Laravel check if relation is empty laravel laravel

Laravel check if relation is empty


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.


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


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;