Laravel provides whereHas so that we can make condition with it. In this tutorial, I will show you how we can write a conditional query with laravel eloquent wherehas. So you will learn laravel wherehas with condition in this tutorial. So if you do not know how to use eloquent wherehas in laravel, then this example is for you.

I will show you an example query of how to use wherehas with condition in laravel 9 application. You have to remember before using it that relationships must exist within the same database.

So let's see the example query of laravel wherehas with condition:



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


And now see the demo output:

        "id": 1,
        "user_id": 1,
        "title": "Maxime non architecto quia in corporis iusto odio beatae.",
        "is_published": 1,
        "created_at": "2023-01-15T04:59:18.000000Z",
        "updated_at": "2023-01-15T04:59:18.000000Z"


Read also: Laravel WhereHas Query Example



Now we know laravel wherehas with condition. Hope this how to use wherehas with condition in laravel tutorial will help you to create laravel 9 wherehas with condition.