Laravel Collection Sum by Item Key

Viewed 711

I have the following Laravel collection $output. I want to sum total for each value of sex 1 and 2. I have tried $output->sum('total') but it gives overall total .

Illuminate\Support\Collection {#1334 ▼
  #items: array:11 [▼
    0 => {#1348 ▼
      +"total": 1037931027.8459
      +"status": 2
      +"sex": 1
    }
    1 => {#1346 ▼
      +"total": 1091237622.0488
      +"status": 2
      +"sex": 2
    }
    2 => {#1342 ▼
      +"total": 1103340160.4262
      +"status": 1
      +"sex": 1
    }
    3 => {#1349 ▼
      +"total": 6004661.498201
      +"status": 4
      +"sex": 1
    }
   ]
 }    
1 Answers

Looking at the documentation you can filter a collection and then sum. Something like this:

$output->whereIn('sex', [1,2])->sum('total')
Related