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

shoaibansari's avatar

How to get count in related tables

i have 2 tables songs and albums.. i want create search function when some one search album title then will be result id,title,image, and total song related that album like 2 or 3 songs ... my search search function are working but problem in related album songs count

Album model

'id', 'artist_id', 'title', 'image', 'description'

public function songs() { return $this->belongsToMany('App\Song', 'songs', 'album_id'); }

Song model

'id', 'artist_id', 'album_id', 'title', 'image', 'file', 'status'

public function album() { return $this->belongsTo('App\Album', 'albums'); }

0 likes
1 reply
grenadecx's avatar
Level 7

Since you use Eloquent, you should try out the withCount to get the related count.

Example:

$albums = Album::withCount('songs')->get();

dd($albums) // You will notice the collection has songs_count for each album.

// For example on the first album
echo $albums[0]->songs_count;

https://laravel.com/docs/5.8/eloquent-relationships Lookup withCount here for further documentation.

Please or to participate in this conversation.