Eloquent Relationship with 3 tables(User > Albums > Photos)

Submitted by ajeeeunni - 1 year ago

Hi, I have 3 tables USER, ALBUMS, PHOTOS USER has one to many relation with ALBUMS, ALBUMS has one to many relation with photos. My relation mapping as follows

USER Model:

class User extends Eloquent
{
protected $table = 'users';
    public function albums()
    {
         return $this->hasMany('Albums', 'user_id');
    }
}

ALBUMS Model:

class Albums extends Eloquent { protected $table = 'albums';
    public function photos()
    {
         return $this->hasMany('Photos', 'user_id');
    }
}

PHOTOS Model:

class Photos extends Eloquent { protected $table = 'photos'; }
In my gallery view:

@foreach(Auth::user()->albums as $album)
{{ $album->name }}
@endforeach
I need to get count of photos in each albums with album name.

Example:

Cars (10)
Bikes (15)
Food (13)

like this

I tried 

{{ $album->photos->count() }}
and 
{{ count($album->photos) }}

first one returns error undefined function count and second one returns 0. 
I tried to print 
var_dump($album->photos)

This return null. 
How can i get count of photos??
comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks