0

Hello Geeks i am stuck here. I am beginner and want to know how to save and update array data in database. this is laravel form requested data

I want to save data like this : mysql database

here is my form request, i want to save data in mysql database, with new row :

"_token" => "FoyoYvFXmNAggbQuMq6PN243QS43MkY99Nq3UAni"
"description" => array:2 [▼
 0 => "<h3>Shared Hosting Plan</h3>"
 1 => "<h3>Cloud Hosting Plan</h3>"
]
"site_id" => array:2 [▼
 0 => "5361"
 1 => "5361"
]
"category_id" => array:2 [▼
 0 => "1"
 1 => "3"
]
"field_1" => array:2 [▶]
"field_2" => array:2 [▶]
"field_3" => array:2 [▶]
"field_4" => array:2 [▶]
"field_5" => array:1 [▶]
"price" => array:2 [▶]
"update_plan" => "Save Plans"
]```


2
  • If you have the control to formulate the Request, I would suggest you to send the request as properly formatted request. Commented Jun 3, 2022 at 8:56
  • php [ ['description' => '<h3>Shared Hosting Plan</h3>', 'site_id' => '5361', 'category_id' => '1'], ['description' => '<h3>Cloud Hosting Plan</h3>', 'site_id' => '5361', 'category_id' => '3'] ] If you can send the request as above, you can deal with it easily in the back-end. Commented Jun 3, 2022 at 8:57

2 Answers 2

1

Try like this

    $save_data=[];
    foreach($data['description'] as $key=>$desc){
        $save_data[]=[
            'description'=>$desc,
            'site_id'=>$data['site_id'][$key],
            'category_id'=>$data['category_id'][$key],
            'feature_field_1'=>$data['field_1'][$key],
            'feature_field_2'=>$data['field_2'][$key],
            'feature_field_3'=>$data['field_3'][$key],
            'feature_field_4'=>$data['field_4'][$key],
            'feature_field_5'=>$data['field_5'][$key],
            'price'=>$data['price'][$key]
        ]
    }
    \DB::table('table')->insert($save_data);
Sign up to request clarification or add additional context in comments.

4 Comments

You should group data and insert multi records : $save_data[] = [...] and move \DB::table('table')->insert($save_data); out foreach
at a time only 1 record insert
you can check document of insert laravel : laravel.com/docs/9.x/queries#insert-statements
You may insert several records at once by passing an array of arrays.
0

You can insert like this

Eloquent approach

Model::insert($data); 

Query Builder approach

DB::table('table')->insert($data);

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.