Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kramsuiluj's avatar

How do you access the loop index on a foreach loop outside the blade template?

By using the @foreach blade template I know that we can access the loop index with this $loop->index, but is there something similar outside the blade template that I can use to access the loop index? Like for example, I want to access the loop index on a model controller.

0 likes
7 replies
jlrdw's avatar

A regular php foreach if in controller.

Sergiu17's avatar
foreach($collection as $index => $item)

you mean this?

1 like
kramsuiluj's avatar

Uhm I mean how do I access the loop index inside the foreach? I have this code:

foreach($request->size as $size) {
            
            $product->sizes()->attach($size, ['price' => $request->"loop index here"]);

        }

I have a data from the request that has a name of price_0, price_1, price_2, So I want to access the loop index so I can get the value of each of them while looping the size.

jlrdw's avatar

Each row increases from 0

$item[0]->whatever

$item[1]->whatever

$item[2]->whatever

Etc

Something like that depending on if it's a complete array or an array of objects.

Snapey's avatar

name your form elements differently and you don't have to mess about with this stuff

if your form items are named like size[] and price[] then your request receives two independent arrays

name them instead like items[]size and items[]price then you end up with a single array you can iterate over where each item has a size and a price attribute

a simple change in your form makes handling the data much easier

kramsuiluj's avatar

Oh thanks a lot, I would never have thought about it, I will try it out, not sure yet how it works.

kramsuiluj's avatar

I've tried what you've said I named them items[]size and items[]price. Sorry I'm quite confused so they're mixed into one array so, how do I access only the sizes or price?

Please or to participate in this conversation.