Saturday, November 16, 2024
Google search engine
HomeLanguagesLaravel Check If Relationship Data is Empty

Laravel Check If Relationship Data is Empty

To check if relationship is empty in laravel; Through this tutorial, you will learn how to check if relationship data or result exists or not in laravel applications.

Let, you have Post model with comments relationship and do you want to check if relationship data is exist or not between Post and comment table in laravel apps? is as follows:

<?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);
    }
}

Laravel Check If Relationship Data is Empty

So, here you will see 4 examples of how to check if relationship exists or not in laravel applications; is as follows:

  • Example 1 – using has() and get() method
  • Example 2 – using count() method
  • Example 3 – using exists() method
  • Example 4 – using relationLoaded() method

Example 1 – using has() and get() method

You can check if relationship data is exist or not between Post and comment table in laravel apps using has() and get() method; is as follow:

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

Example 2 – using count() method

You can check if relationship data is exist or not between Post and comment table in laravel apps using count() method; is as follow:

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

Example 3 – using exists() method

You can check if relationship data is exist or not between Post and comment table in laravel apps using exists() method; which is as follow:

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

Example 4 – using relationLoaded() method

You can check if relationship data is exist or not between Post and comment table in laravel apps using relationLoaded() method; is as follow:

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

Conclusion

To check if relationship is empty in laravel; Through this tutorial, you have learned how to check if relationship exists or not in laravel applications.

Recommended Laravel Tutorials

RELATED ARTICLES

Most Popular

Recent Comments