Laravel Check If Relationship Is Empty Or Not Example

In this tutorial, I will show you laravel check if relationship is empty or not. It is good practice to print relationship data after checking whether there is data or not. If not then we can print a message to get better experience. So if you do not know laravel empty relationship then this example if for you. This source code will work in laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9 versions.

If we would like to check whether your relation data is empty or not in laravel then I will help you with several ways to check the relationship empty or not in laravel. We can see the following ways to check if a relation is empty in laravel. Let's see the example code:

app/Models/Post.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 for your blade file:

@if($post->comments()->exists())
   {{-- Post has comments --}}
@else
   {{-- Post does not have comments --}}
@endif

//another solution

@if($post->comments->count())
   {{-- Post has comments --}}
@else
   {{-- Post does not have comments --}}
@endif

//another solution

@if($post->comments->count())
   {{-- Post has comments --}}
@else
   {{-- Post does not have comments --}}
@endif

//another is

@if($post->relationLoaded('comments'))
   {{-- Post has comments --}}
@else
   {{-- Post does not have comments --}}
@endif

 

Read also: Count Weekend Days Between Two Dates Using Carbon in Laravel

 

Hope it can help you.

 

#laravel