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

User1980's avatar

How to return count + collection data in relationships

Hi all,

I am trying to return the completed and pending sales of each active user in a single table. But I cannot work out how to do a count while returning the collection.

Right now this returns the collection correctly $results= User::with('sales')->where('status', 'active')->get();

I was hoping for something like this:

         $results= User::with('sales')
          //count  sales.completed as completedSales
          //count  sales.pending as pendingSales
           ->where('status', 'active')
          ->get();

Is this actual possible as I cannot get it to work.

Thanks.

0 likes
4 replies
User1980's avatar

I cannot thank you enough, I was actually going in the wrong direction, this is where I was at:

User::with(['sales' => function ($query) {
            $query->selectRaw("SUM(CASE type WHEN 'completed' then 1 else null end) as completed_sales_count");
            $query->selectRaw("SUM(CASE type WHEN 'pending' then 1 else null end) as pending_sales_count");
            }])
->where('status', 'active')->get();
User1980's avatar

My apology, i had a long call in between...this is why I am late in clicking "Best answer" :-)

Please or to participate in this conversation.