Reputation:
I have form to send products id with qty for each product my form:
<select name="products[][product_id]">
@foreach($products as $product)
<option value="{{ $product->id }}">{{ $product->trade_name }}</option>
@endforeach
</select>
<input type="text" name="products[][quantity]">
With this name
style I got like this:
"products" => array:4 [▼
0 => array:1 [▼
"product_id" => "1"
]
1 => array:1 [▼
"quantity" => "2"
]
2 => array:1 [▼
"product_id" => "2"
]
3 => array:1 [▼
"quantity" => "3"
]
]
I need to achieve the array like this:
"products" => array:2 [▼
0 => array:1 [▼
"product_id" => "1",
"quantity" => "2"
]
1 => array:1 [▼
"product_id" => "2",
"quantity" => "3"
]
]
Upvotes: 1
Views: 231
Reputation: 897
select name="products[product_id][]">
@foreach($products as $product)
<option value="{{ $product->id }}">{{ $product->trade_name }}</option>
@endforeach
</select>
<input type="text" name="products[quantity][]">
If you specify the keys first, and then create a nested array for those (opposite to what you have done) then when you need to access them you can loop through them and access the corresponding entry e.g
$combined_array = [];
foreach($request->products['product_id'] as $key => $value) {
$combined_array[] = [
'product_id' => $value,
'quantity' => $request->products['quantity'][$key]
];
}
$combined_array
should then have your data.
Upvotes: 1