From this laravel withcount condition tutorial, we will learn some tips that how to use condition with withcount in laravel. Sometimes you may face that condition that you need to pass a condition with your laravel elquent withcount query. I will retrieve all the posts whose comments are not approved. 

I will write this query with laravel elquent withcount. First I will fetch all posts then I will count all the comments of every post then I will pass a condition to make this laravel withcount condition. You can call it as a laravel withcount subquery.

laravel-withcount-condition

Now use that in a controller like this to get laravel condition withcount:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class TutorialController extends Controller
{   
    public function index()
    {   
        return Post::where('is_published', true)
                    ->withCount([
                        'comments as total_comments_count' => function ($query) { 
                            $query->where('is_approved', false);
                        }
                    ])
                    ->first();
    }
}

 

Now see the output:

{
	"id": 1,
	"user_id": 1,
	"title": "Eius quia id consequatur mollitia dolor totam debitis facere. Reiciendis non magni sed. Itaque ducimus labore nemo",
	"is_published": 1,
	"created_at": "2023-01-22T12:22:48.000000Z",
	"updated_at": "2023-01-22T12:22:48.000000Z",
	"total_comments_count": 2
}

 

Read also: Laravel WithCount Greater Than Condition Example

 

Conclusion

In this laravel withcount condition tutorial,  I have tried my best to let you know the clear concept of laravel 9 withcount condition. Hope now after completing this withcount with condition laravel tutorial, you will know how to use laravel condition withcount example.