We already know that laravel withcount gives us related model count. But it is not enough sometimes. Sometimes we need more like we need to pass a callback or closure to make it laravel withcount greater than query. In this tutorial, I will share a laravel query with withcount that how to use withcount with greater than condition. To create this laravel withcount greater than tutorial, I will use Post model and i will fetch only those posts which have more than 2 comments.

For this greater than condition with laravel withcount, we have to use laravel has method. So let's see how to use withcount in laravel with callback:

laravel-withcount-with-greater-than-example

Now use that in a controller like this:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class TutorialController extends Controller
{   
    public function index()
    {   
        return Post::has('comments', '>=' , 1)
                    ->with('comments')->get();
    }
}

 

Now see the output of this laravel withcount callback query:

[
	{
		"id": 1,
		"user_id": 1,
		"title": "Eius quia id consequatur mollitia dolor totam debitis facere. Reiciendis non magni sed. Itaque ducimus labore nemo ipsa unde voluptas. In repellendus quo expedita adipisci qui aut. Labore molestias est voluptatem.",
		"is_published": 1,
		"created_at": "2023-01-22T12:22:48.000000Z",
		"updated_at": "2023-01-22T12:22:48.000000Z",
		"comments": [
			{
				"id": 1,
				"post_id": 1,
				"user_id": 1,
				"comment": "Magni eveniet itaque ratione atque.",
				"is_approved": 0,
				"created_at": "2023-01-22T12:22:48.000000Z",
				"updated_at": "2023-01-22T12:22:48.000000Z"
			},
			{
				"id": 2,
				"post_id": 1,
				"user_id": 1,
				"comment": "Fugiat recusandae ipsam veniam unde necessitatibus ratione facilis eum.",
				"is_approved": 0,
				"created_at": "2023-01-22T12:22:48.000000Z",
				"updated_at": "2023-01-22T12:22:48.000000Z"
			}
		]
	},
	{
		"id": 2,
		"user_id": 2,
		"title": "Similique sunt ex placeat quae cupiditate. Sapiente ullam omnis recusandae ipsa sed ut deleniti. Mollitia quis magni voluptatem qui unde.",
		"is_published": 1,
		"created_at": "2023-01-22T12:22:48.000000Z",
		"updated_at": "2023-01-22T12:22:48.000000Z",
		"comments": [
	        {
				"id": 3,
				"post_id": 2,
				"user_id": 2,
				"comment": "Quibusdam quo reiciendis incidunt pariatur aut et.",
				"is_approved": 0,
				"created_at": "2023-01-22T12:22:48.000000Z",
				"updated_at": "2023-01-22T12:22:48.000000Z"
			}
		]
	}
]

 

Read also: Laravel WithCount In Model Query Example

 

Conclusion

In this laravel withcount greater than tutorial,  I have tried my best to let you know the clear concept of laravel withcount callback. Hope now after completing this laravel has tutorial, you will know how to use withcount in laravel with callback.