1

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?

panthro
  • 22,779
  • 66
  • 183
  • 324

1 Answers1

3

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

Community
  • 1
  • 1
Needpoule
  • 4,476
  • 24
  • 33
  • Thanks, so as a accessor the count will come out every time eloquent is called? Is this not wasteful? – panthro May 29 '15 at 10:56
  • The count is simply the php function. It does not perform a sql query every time. – Needpoule May 29 '15 at 12:25
  • So every time I call the model will the php do a count? This is what I mean by wasteful - I do not need a count on all() for example. – panthro May 29 '15 at 13:05