Search code examples
laravellaravel-4eloquentlaravel-5

Counting a many to many relationship?


I have a many to many relationship between users and images.

User Model

public function image()
{
    return $this->belongsToMany('\App\Image');
}

Image Model

public function user()
{
    return $this->belongsToMany('\App\User');
}

Tables

users

id | name

images

id | url

image_user

id | image_id | user_id

When a user 'favourites' an image, it's stored in the pivot table.

id | image_id | user_id
 1      1          1
 2      2          1
 3      1          2

I need a count of each images favourites.

I try something like:

 Image::with('user')->find(1)->count();

But this counts the number of users, not the number of favourites.

Ideally I would like to return all of the image data along with a count of the user data - how can I do this?


Solution

  • You can do this:

    $image = Image::with('user')->find(1) // Get the image with user eager loading
    $image->name; // Access any attribute
    $image->users->count(); // Get the user count
    

    You can even add a few lines in your Image model to create a "custom" attribute:

    public function getFavoritesAttribute()
    {
        return count($this->users);
    }
    

    And then use it like this:

    $image->favourites;
    

    There is a more detailed solution here: Laravel many to many loading related models with count

    EDIT: You can now use the withCount() method, that will count the number of related model without actually loading them.

    In your case it will look like this:

    $image = Image::withCount('user')->find(1);
    $image->user_count
    

    For more details: https://laravel.com/docs/master/eloquent-relationships#counting-related-models