It is good practice to write reusable code in every application. Cause reusable code helps us to use them any place anywhere without any pain. In this tutorial, I will show you how we can write reusable code in laravel application and use them in controller.

To create this laravel withcount in model tutorial, I will write a query in the Post model and fetch data from controller. Hope you will learn how to write queries in the model and use them in the controller.

To create laravel withcount in model tutorial, first update the Post model like:

app\Models\Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Post extends Model
{
    use HasFactory;

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
    
    public function getPost()
    {
        return $this::withCount(['comments']);
    }
}

 

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(Post $post)
    {   
        return $post->getPost()
                    ->orderBy('id','desc')
                    ->get();
    }
}

 

Now let's see the output of laravel withcount in model:

[
    {
        "id": 2,
        "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": 1,
        "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 Eloquent WithCount OrderBy Query Example

 

Conclusion

In this laravel withcount in model tutorial,  I have tried my best to let you know the clear concept of withcount in model query example laravel. Hope now after completing this tutorial, you will know how to write query in model in laravel.