Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ajeeeunni's avatar

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

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??

0 likes
4 replies
ARCANEDEV's avatar

Try to fix your models by using a singular name for each class and check also the namespaces:

namespace YourModelsNamespace;

class User extends Eloquent
{
    protected $table = 'users';

    public function albums()
    {
         return $this->hasMany('YourModelsNamespace\Album');
    }
}
namespace YourModelsNamespace;

class Album extends Eloquent
{
    protected $table = 'albums';

    public function photos()
    {
         return $this->hasMany('YourModelsNamespace\Photo');
    }
}
namespace YourModelsNamespace;

class Photo extends Eloquent
{
    protected $table = 'photos';
}

And use the load() method to eager load the relationships:

@foreach(Auth::user()->load('albums', 'albums.photos')->albums as $album)
    {{ $album->name . ' (' . $album->photos->count() . ')' }} 
@endforeach
4 likes
ajeeeunni's avatar

Hi ARCANEDEV,

I tried your solution but am getting an error

Call to undefined method

Illuminate\Database\Query\Builder::photos()

And am using LARAVEL 4.2

ajeeeunni's avatar

I checked but could n't find photos in list :(

When I tried Albums::find(static id)->photos->count in controller, it worked well

Please or to participate in this conversation.