Home > OS >  Laravel - How to insert multi-dimensional Array in DB
Laravel - How to insert multi-dimensional Array in DB

Time:12-01

I have the array as below;

enter image description here

I'd like to insert each name keys into tableName and get the inserted id. For the steps, each of them will be inserted into another table tableSteps including the last inserted id of the name.

Like as below screenshot.

enter image description here

In my controller,

Here's what I've done so far.

    $instructionsArrays = $request->instructions;
    $max = count($instructionsArrays);

    for ($x = 1; $x <= $max; $x  ) {
        foreach($instructionsArrays as $instructionsArray){
            Instruction::updateOrCreate(
                ['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $x],
                ['name' => $instructionsArray['name']],
            );
        }
    }

I was able to save sequence numbers but for names it saves only the last name key. And... I'm really lost..

CodePudding user response:

You can achieve what you want from 2 for loops

foreach($request->instructions as $key => $val){
$id = Instruction::insertGetId(
    ['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $key   1],
    ['name' => $val['name']],
);
$data = []; //bulk insertion
$created_at = now();
foreach($val["steps"] as $step){
    array_push($data, ["header_id" => $id, "name" => $step, "sequence" => $key 1, "created_at" => $created_at]); //why insert sequence when you can obtain it from the relationship?
  }
  Steps::insert($data);
 }

CodePudding user response:

With the help of the answer of @Kneegrows, I came up with the code below and it is now working. Thank you.

        foreach ($request->instructions as $key => $val) {
         $instruction = Instruction::updateOrCreate(
                ['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $key   1],
                ['instructions_name' => $val['name']],
            );
        $id = $instruction->id;
        $data = []; //bulk insertion
        $i = 1;
        foreach ($val["steps"] as $step) {
            if(!is_null($step)){
                array_push($data, ["instruction_id" => $id, "steps_name" => $step, "sequence" => $i]);
                $i  ;
            }
        }
        Steps::insert($data);
    }
  • Related