Darama
Darama

Reputation: 3370

How to rewrite loop to collection functions in Laravel?

I have loop, that iterates collection and find object, that has status = 1, after remove that.

How to rewrite this code on collections functions in Laravel?

$announcements->every(function ($value) use ($announcements) {
            foreach($value->offers as $k => $v) {
                if ($v->status == 1) {
                    unset($value->offers[$k]->publisher);
                }
            }
        });

Upvotes: 0

Views: 96

Answers (1)

Filip Sobol
Filip Sobol

Reputation: 5491

Actually every() method checks if all items in the collection return true. You should use each() method instead, to loop through all items and check them individually.

Also if you want to remove some items from the collection, you can use filter() method:

$fitlered = $announcements->filter(function($value) {
    return $value->status !== 1;
});

Upvotes: 1

Related Questions