Laravel Laravel Collections Cheatsheet - everything you need to know

Laravel Laravel Collections Cheatsheet

How to find the average value of items in a Laravel Collection?

Use the avg() method. You can provide a value indicating which key to average (first example) or not (2nd example).

  1. $average = collect(
  2.         [
  3.                 ['foo' => 10],
  4.                 ['foo' => 10],
  5.                 ['foo' => 20],
  6.                 ['foo' => 40]
  7.         ]
  8.         )->avg('foo');
  9.  
  10. // 20
  11.  
  12. $average = collect(
  13.         [1, 1, 2, 4]
  14.         )->avg();
  15.  
  16. // 2
View More Details (and 3 discussions about this topic) Here...