Jaroslav Klimčík
Jaroslav Klimčík

Reputation: 4808

Increment in Laravel collection

I have a collection and I would like to increment values if the condition is met. I want to use map() method to iterate and return array (or collection) with total counts. So far I have this:

   $counts = [
        'notChecked' => 0,
        'published' => 0,
        'total' => 0
    ];

    $this->reviewPhotosRepository->getByHotelId($hotel_id)->map(function($photo) use (&$counts) {
        $photo->checked ?: $counts['notChecked']++;
        $photo->published ?: $counts['published']++;
        $counts['total']++;
    });

    return $counts;

It works but I think it looks quite odd and it is not such a 'laravelish' way. Is there any other option to look it a little better?

Upvotes: 0

Views: 1466

Answers (1)

Travis Britz
Travis Britz

Reputation: 5552

Instead of map(), you could use reduce():

return $this->reviewPhotosRepository
    ->getByHotelId($hotel_id)
    ->reduce(function ($carry, $item) {
        $carry['notChecked'] += $item['checked'] ? 1 : 0;
        $carry['published'] += $item['published'] ? 1 : 0;
        $carry['total'] += 1;
        return $carry;
    }, [
        'notChecked' => 0,
        'published' => 0,
        'total' => 0
    ]);

Is it better? Well, you know, that's just, like, your opinion, man.

Upvotes: 1

Related Questions