Laravel Check Relationship Data Is Empty
Today, we will learn How to check Laravel Check Relationship Data Is Empty? If you want to check whether your relation data is empty or not in Laravel, then you are in the right place. I will give a very simple way to check whether your relationship is empty or not in Laravel. I would like to show you how to check whether Laravel relation data is empty or not empty.
In this tutorial, I explained step by step to check whether Laravel eloquent relationship is empty or not. Also, You can use this example with Laravel6, Laravel7, Laravel8, and Laravel9 versions.
Table of Contents
Laravel Check Relationship Data Is Empty
<?php #app/Models/Posts.php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Posts extends Model { use HasFactory; /** * Write code on Method * * @return response() */ protected $fillable = [ 'title', 'body' ]; /** * Get the comments for the blog post. */ public function comments() { return $this->hasMany(Comments::class); } }
Using get method
You can filter models that do not have any related items.
@if($posts->has("comments")->get())
{{-- Post has comments --}}
@else
{{-- Post does not have comments --}}
@endif
Using count method
Model to you already have loaded the collection, and you can call the count() method of the collection.
@if($posts->comments->count())
{{-- Post has comments --}}
@else
{{-- Post does not have comments --}}
@endif
Using exists
If you want to check without loading the relation, then you can run a query on the relation.
@if($posts->comments()->exists())
{{-- Post has comments --}}
@else
{{-- Post does not have comments --}}
@endif
using relationLoaded
You want to check if the collection was eager loaded or not.
@if($posts->relationLoaded('comments'))
{{-- Post has comments --}}
@else
{{-- Post does not have comments --}}
@endif