Summer Sale! All accounts are 50% off this week.

ahsan's avatar
Level 46

foreach loop is better or should use collection?

we have items array want to attach

this code is working fine for me.

i just want to know this approach is better or something else better solution?

foreach ($this->request->items as $item) {
    $sale->items()->attach([
        $item['item']['id'] => ['quantity' => $item['quantity']]
    ]);
}

i used with collection too but foreach method is neat and clean.

$collection = collect($this->request->items);

$items = $collection->mapWithKeys(function ($item) {
    return [$item['item']['id'] => ['quantity' => $item['quantity']]];
})->all();

$sale->items()->attach($items);

i'm asking just for best practices.

both are working fine.

0 likes
2 replies
Cronix's avatar

They are really both loops, doing the same thing. ->mapWithKeys() is a loop.

So, for me, it comes down to whatever is shortest, AND most clear, AND most efficient. I'd go with option 1 in this case.

It takes slightly longer and uses slightly more resources to create a collection just so you can iterate over it, when you can just iterate over the original array without converting it first.

1 like
jmurphy1267's avatar

Before deciding on an implantation try ask the question "Who is going to view my code and would I be able to easily read it 6 months later".

Please or to participate in this conversation.