Reputation: 1051
I'm making a recipe book and for the recipe steps I want the (index + 1) of the array to be saved as the step number, doing (index + 1) so that the numbers start on 1, when I'm saving on the controller how would I do this?
This is how I was doing it with the user adding the step number manually, how do I save in the "number"
the index + 1?
if ($request->has('steps')) {
$steps = [];
$recipe_id = $recipe->id;
foreach ($request->get('steps') as $item) {
$num = $item['number'];
$duration = $item['duration'];
$instructions = $item['instructions'];
if (isset($num, $duration, $instructions)) {
$steps[] = [
"number" => $num,
"instructions" => $instructions,
"duration" => $duration,
"recipe_id" => $recipe_id
];
}
}
if (count($steps)) {
Step::insert($steps);
}
}
Upvotes: 0
Views: 86
Reputation: 11034
I think this is standard PHP array foreach operation, the index of an item in a non multi dimensional array is the key
foreach ($request->get('steps') as $number => $item) {
$number = $number++;
Hope this helps
Upvotes: 1