PHP

Efficient Relationship Counting with `withCount` and `withExists`

Optimize Laravel Eloquent queries by efficiently counting related models without loading the full relationship, using `withCount` and `withExists` for performance.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

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

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

    // Example usage:
    // $users = User::withCount('posts')->get();
    // foreach ($users as $user) {
    //     echo $user->name . ' has ' . $user->posts_count . ' posts.';
    // }

    // $users = User::withExists('comments')->get();
    // foreach ($users as $user) {
    //     echo $user->name . ' has comments: ' . ($user->comments_exists ? 'Yes' : 'No');
    // }

    // Combining with constraints:
    // $users = User::withCount(['posts' => function ($query) {
    //     $query->where('is_published', true);
    // }])->get();
}
How it works: This snippet demonstrates `withCount` and `withExists` for efficiently querying the number or presence of related models without eager loading the entire relationship collection. `withCount('relation')` adds a `relation_count` attribute to the parent model, containing the total count of related items. `withExists('relation')` adds a `relation_exists` boolean attribute, indicating if any related items exist. Both methods are significantly more performant than loading the relationship and then counting/checking in PHP, as they perform the count/existence check directly in the SQL query.

Need help integrating this into your project?

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

Hire DigitalCodeLabs