Search code examples
phplaravellaravel-6laravel-collection

Laravel higher order message unexpected result


I have a higher order message in laravel. It looks like this:

$category->scores->each->ratings->where('result.rating', '>=', 3)->count();

A category has scores a score has ratings and a rating has a result.

I want to get the total amount of ratings for every category where >= 3.

With the code I have right now the end result is always 0.

But when I loop over it like this:

@foreach($categories as $category)
    @foreach($category->scores as $score)
        @foreach($score->ratings->where('result.rating', '>=', 3) as $rating)
            {{ $rating->result->result_nl }}
        @endforeach
    @endforeach
@endforeach

There are 3 rating results.

What is wrong with my higher order message?


Solution

  • There are a few misunderstandings of Higher Order Functions in your question. In the documentation and in Laravel implementation they use method calls.

    Here you are trying to do a sum on an each call, each does not return anything, but is a Collection method to be an alternative to foreach.

    If you add the following function to the score model.

    public function ratingsOverTree()
    {
        return $this->ratings->where('result.rating', '>=', 3)->count();
    }
    

    You can use the sum method to add together the results, with the usage of the ratingsOverTree() method.

    $category->scores->sum->ratingsOverTree();