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.
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.
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
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?