Avoid WhereHas And Use WhereRelation In Laravel

Hello artisan

In this tutorial tutorial, I am going to discuss about whereRelation laravel code example. You already know that how to use whereHas with relationship. That mean using this whereRelation you can write shortcut of whereHas.

So in this example i will share source code of whereRelation so that you can understand better. Laravel released this feature in their latest laravel released. So let' see the example code:

Before releasing whereRelation, we did like that

User::whereHas('posts', function ($query) {
    $query->where('published_at', '>', now());


But having released whereRelation, we can do it in the below way in Laravel 8.x version.

whereRelation Laravel Example:

User::whereRelation('posts', 'published_at', '>', now())->get();


Read also: Laravel Eloquent Relationship withDefault Code Example


Hope it can help you.


#laravel #laravel-8x #eloquent-relationship