@ahmednaser Did you try withCount?
$channels = Channel::withCount('users')->get();
https://laravel.com/docs/7.x/eloquent-relationships#counting-related-models
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have 2 modules channels and users I want to return the users count when selecting a specific channel, so I made an eloquent relationship in channels model users() but the performance is a bit bad so I made a lot of googling and I ended up with using nested query. so how can I make something like this in laravel
// Model Relationship
public function users()
{
return $this->belongsToMany(User::class, 'channel_user');
}
// Channel Transformer
public function transform(Channel $channel)
{
return [
'code' => (string) $channel->code,
'name' => (string) $channel->name,
];
}
public function includeUsersCount($channel)
{
return $this->primitive($channel->users()->get()->count());
}
@ahmednaser Yeah you can do it like.
$channel = Channel::with('users')->withCount('users')->first();
Please or to participate in this conversation.