Laravel Check If Relationship Data is Empty Example
Hi Guys,
Today, I will let you know example of laravel check if relationship is empty. This example will help you laravel check if relationship exists. I would like to show you how to check relation data is empty laravel. I explained simply step by step check if eloquent relationship is empty laravel.
You can use this example with laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 versions.
If you want to check whether your relation data is empty or not in laravel then i will help you with several ways to check whether your relationship is empty or not in laravel. you can see the following ways to check if a relation is empty in laravel.
First, i will create sample Post model with comments relationship. so, let's see the following post model code:
app/Models/Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
/**
* Write code on Method
*
* @return response()
*/
protected $fillable = [
'title', 'body', 'status'
];
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany(Comment::class);
}
}
Now, let's see the following solutions:
Solution 1:
Code:
@if($post->has("comments")->get())
{{-- Post has comments --}}
@else
{{-- Post does not have comments --}}
@endif
Solution 2:
Code:
@if($post->comments->count())
{{-- Post has comments --}}
@else
{{-- Post does not have comments --}}
@endif
Solution 3:
Code:
@if($post->comments()->exists())
{{-- Post has comments --}}
@else
{{-- Post does not have comments --}}
@endif
Solution 4:
Code:
@if($post->relationLoaded('comments'))
{{-- Post has comments --}}
@else
{{-- Post does not have comments --}}
@endif
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Eloquent whereHas() Condition Example
- Laravel Replicate Model with Relationships Example
- Laravel Collection Has Method Example
- Laravel Order By Relation Column Example
- How to use whereHas with orWhereHas in Laravel?
- Laravel Order By Relationship Sum Column Example
- Laravel Relationship Eager Loading with Condition Example
- Laravel Relationship Eager Loading with Count Example
- Laravel Relationship Where Condition Example
- Laravel Eloquent Relationships Tutorial From Scratch
- Laravel Has Many Through Eloquent Relationship Tutorial
- Laravel One to Many Polymorphic Relationship Tutorial
- Laravel Many to Many Polymorphic Relationship Tutorial