We can check relationship existence in laravel using has() method. But sometimes it is not enough to go. We need more power. In this case, laravel provides whereHas() method. So in this example, I will show you how to use laravel 9 wherehas and write a query with this eloquent whereHas() in laravel 9 application.

Using whereHas() we can pass a closure to make a condition in our query like you can add where or anything you want. That means we can overcome the drawback of laravel has() method with this whereHas() method. 

Let's see the example code of laravel wherehas example:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Contracts\Database\Eloquent\Builder;

class TutorialController extends Controller
{   
    public function index()
    {   
        return Post::whereHas('comments', function (Builder $query) {
            $query->where('is_published', true);
        })->get();
    }
}

 

Now see the output like:

[
    {
        "id": 1,
        "user_id": 1,
        "title": "Maxime non architecto quia in corporis iusto odio beatae. Harum cupiditate libero dicta et fuga vero. Autem facere id reprehenderit consectetur.",
        "is_published": 1,
        "created_at": "2023-01-15T04:59:18.000000Z",
        "updated_at": "2023-01-15T04:59:18.000000Z"
    }
]

 

Read also: Laravel Query Relationship Existence Example

 

Conclusion

Now we know laravel 9 wherehas. Hope this laravel wherehas example tutorial will help you to create laravel wherehas relationship.