PHP

Performing Aggregations on Related Models with withCount

Optimize your Laravel Eloquent queries by using `withCount` to efficiently retrieve the count of related models without loading the entire relationship, improving performance.

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Comment; // Assuming Comment model exists

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

// Usage example in a controller or service:
// $posts = Post::withCount('comments')->get();
//
// foreach ($posts as $post) {
//     echo "Post: {$post->title}, Comments: {$post->comments_count}
";
// }

// Using withCount with a custom alias
// $postsWithApprovedCommentCount = Post::withCount([
//     'comments as approved_comments_count' => function ($query) {
//         $query->where('approved', true);
//     }
// ])->get();
//
// foreach ($postsWithApprovedCommentCount as $post) {
//     echo "Post: {$post->title}, Approved Comments: {$post->approved_comments_count}
";
// }
How it works: The `withCount` method allows you to efficiently count the number of related models for each parent model without having to load the entire relationship. This is particularly useful for displaying counts (e.g., number of comments on a post) in lists, significantly reducing the number of queries and memory usage compared to loading all related models and then counting them in PHP. You can also apply conditions to the count using a closure.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs