0

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);
    }
}

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.