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 and laravel 9 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 AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;

use IlluminateDatabaseEloquentModel;

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

.medrectangle-4-multi-155{border:none!important;display:block!important;float:none!important;line-height:0;margin-bottom:15px!important;margin-left:0!important;margin-right:0!important;margin-top:15px!important;max-width:100%!important;min-height:250px;min-width:300px;padding:0;text-align:center!important}

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…

Leave a Comment