Laravel Check If Relationship Data is Empty Example

By Hardik Savani April 16, 2024 Category : Laravel

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, laravel 10 and laravel 11 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...

Tags :
Shares