We know that, using withCount in our laravel eloquent query, we can count relational model rows. We can create an alias with laravel withCount also. In this tutorial, we will see how to use withcount with orderby. I will fetch some posts with comments count and I will orderby that post with desc according to comments count. 

How we can write that eloquent query to create an example of laravel withcount orderby. So let's see the example query of laravel 9 withcount orderby:

laravel-withcount-orderby

Now see the controller example code of how to write query with withcount in laravel with orderby.

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class TutorialController extends Controller
{   
    public function index()
    {   
        return Post::withCount('comments')
                    ->orderBy('comments_count', 'desc')
                    ->get();
    }
}

 

Now let's see the output of laravel 9 withcount orderby:

[
    {
        "id": 1,
        "user_id": 1,
        "title": "Eius quia id consequatur mollitia dolor totam debitis facere.",
        "is_published": 1,
        "created_at": "2023-01-22T12:22:48.000000Z",
        "updated_at": "2023-01-22T12:22:48.000000Z",
        "comments_count": 2
    },
    {
        "id": 2,
        "user_id": 2,
        "title": "Similique sunt ex placeat quae cupiditate.",
        "is_published": 1,
        "created_at": "2023-01-22T12:22:48.000000Z",
        "updated_at": "2023-01-22T12:22:48.000000Z",
        "comments_count": 1
    }
]

 

Read also: Laravel WithCount Nested Relationship Example

 

Conclusion

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