Using collection method reduce()

reduce() method is used to get single result from eloquent collection

Suppose, we need to do summation on each rating field in ratings tbl to get accumulated points, we can implement this using reduce()

Code snippet will be like below.

$ratings = Rating::all();

$totalPoints = $ratings->reduce( function( $carry, $rating ) {
    return $carry + $rating->rating;
}, 0); // default value for carry is set to 0

Above, reduce() method takes two parameters - carry which is set to 0 initially and collection item in each iteration.

One other thing to note, the above result can also be achieved with collection sum() method like below

$ratings = Rating::all();
$ratings->sum('rating');

Related Posts