Laravel check if relation is empty
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() ) {
// ...
}
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.