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

AhmedNaser's avatar

Eloquent nested query

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());
    }

0 likes
4 replies
AhmedNaser's avatar

yes, it's the same thing, what I want to do is getting channel, users and user count in one nested query

MichalOravec's avatar
Level 75

@ahmednaser Yeah you can do it like.

$channel = Channel::with('users')->withCount('users')->first();

Please or to participate in this conversation.