You can fetch specific data with a select statement like Model::select(['id','title']) like this. In this tutorial, we will fetch only specific fields with select using withcount in laravel. But remember, before using withCount with a select statement, keep in mind that you call withCount after the select method.

Now in this example tutorial, I will fetch post id and title with the number of every post comments count. To write this query, I will use laravel withcount select statement.

laravel-withcount-select

Now use that in a controller like this to get use select with withcount laravel.

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class TutorialController extends Controller
{   
    /**
     * Tutorial from LARAVELIA
     */
    public function index()
    {   
        return Post::select(['id','title'])
                    ->withCount('comments')
                    ->get();
    }
}

 

Now see the output:

[
    {
        "id": 1,
        "title": "Eius quia id consequatur mollitia dolor totam debitis facere.",
        "comments_count": 2
    },
    {
        "id": 2,
        "title": "Similique sunt ex placeat quae cupiditate.",
        "comments_count": 1
    }
]

 

Read also: Laravel WithCount Condition Eloquent Query Example

 

Conclusion

In this laravel withcount select tutorial,  I have tried my best to let you know use select with withcount laravel. Hope now after completing this how to use select with withcount in laravel tutorial, you will know laravel select withcount.