'laravel 5.6 bulk inserting json data

I am trying to build an API to store and retrieve MCQ exam papers. I am using laravel resource class to send handle Json data. I need to insert 40 records into MySQL database in a single query without using multi dimensional arrays. Is there any method available?

Sample data from front end:

{
"data":[
    {
    "paper_id":"5",
    "question_no":"2",
    "question":"test insert code",
    "answer1":"answer1",
    "answer2":"answer2 ",
    "answer3":"answer3 ",
    "answer4":"Answer4 ",
    "answerC":"Correct Answer",
    "knowarea":"who knows!"

    },

    {
        "paper_id":"5",
        "question_no":"3",
        "question":"test insert code",
        "answer1":"answer1",
        "answer2":"answer2 ",
        "answer3":"answer3 ",
        "answer4":"Answer4 ",
        "answerC":"Correct Answer",
        "knowarea":"who knows!"

    },

    {
        "paper_id":"5",
        "question_no":"4",
        "question":"test insert code",
        "answer1":"answer1",
        "answer2":"answer2 ",
        "answer3":"answer3 ",
        "answer4":"Answer4 ",
        "answerC":"Correct Answer",
        "knowarea":"who knows!"

    },

    {
        "paper_id":"5",
        "question_no":"5",
        "question":"test insert code",
        "aanswer1":"answer1",
        "answer2":"answer2 ",
        "answer3":"answer3 ",
        "answer4":"Answer4 ",
        "answerC":"Correct Answer",
        "knowarea":"who knows!"

    }
]

}`

The front end send 40 such objects i need to bulk insert them into my database. The below code is my controller store function,

`   $paper->paper_id = $request->input('paper_id');
    $paper->question_no = $request->input('question_no');
    $paper->question = $request->input('question');
    $paper->answer1 = $request->input('answer1');
    $paper->answer2 = $request->input('answer2');
    $paper->answer3 = $request->input('answer3');
    $paper->answer4 = $request->input('answer4');
    $paper->answerC = $request->input('answerC');
    $paper->knowarea = $request->input('knowarea');

    if($paper->save())
    {
        return new ExamPaperResource($paper);
    }

What are my choices for bulk inserting the data?



Solution 1:[1]

This code works for me. It inserted all 40 records with no problems.

$array = $request->all();
    foreach($array["data"] as $row)
    {
        Exam_Paper::create(['paper_id'      => $row["paper_id"],
                            'question_no'   => $row["question_no"],
                            'question'      => $row["question"],
                            'answer1'       => $row["answer1"],
                            'answer2'       => $row["answer2"],
                            'answer3'       => $row["answer3"],
                            'answer4'       => $row["answer4"],
                            'answerC'       => $row["answerC"],
                            'knowarea'      => $row["knowarea"],
        ]);

    }

Solution 2:[2]

Based on your sample data, you can json_decode the data and then use a single Model::insert():

{
  "data":[
    {
      "paper_id":"5",
      "question_no":"2",
      "question":"test insert code",
      "answer1":"answer1",
      "answer2":"answer2 ",
      "answer3":"answer3 ",
      "answer4":"Answer4 ",
      "answerC":"Correct Answer",
      "knowarea":"who knows!"
    },
    ...
  ]
}

// Controller.php
public function store($json)
{
    $data = json_decode($json, true);
    Paper::insert($data);
}

That will create arrays from your json and then insert all the records at once.

Solution 3:[3]

You can use: Eloquent::insert()

Like example below.

$data = array(
    array('name'=>'Coder 1', 'rep'=>'4096'),
    array('name'=>'Coder 2', 'rep'=>'2048'),
    //...
);

Coder::insert($data);

Solution 4:[4]

Try code below

$jsonarray =json_decode(json_encode($b),TRUE); // $b=your json array
foreach ($jsonarray as $key => $value) 
{
 foreach ($value as $a => $b) 
  {
  $qry=DB::insert('insert into your_table(colomn_name1,colomn_name2)values(?,?)',[$b['indexname1'],$b['indexname2']]); //index name will be paper_id,question_no etc
  }
}

your code will look like this

public function bulkdata(Request $request)
  {

   $b=$request->input('data');
$jsonarray =json_decode(json_encode($b),TRUE);
foreach ($jsonarray as $key => $value) 
{

 foreach ($value as $a => $b) 
  {

  $qry=DB::insert('insert into yourtable(paper_id,question_no,question,answer1,answer2,answer3,answer4,answerC,knowarea)values(?,?,?,?,?,?,?,?,?)',[$b['paper_id'],$b['question_no'],$b['question'],$b['answer1'],$b['answer2'],$b['answer3'],$b['answer4'],$b['answerC']$b['knowarea']);
  }
}         

}

Solution 5:[5]

insert select query with update models array field

$newModelsArray=ModelTable::where(....)->get();


            foreach ($newModelsArray as $objectItr) {

            $newObjectItr = $objectItr->replicate();
            $newObjectItr->field=newValue;
            $newObjectItr->save();
            }

and there you'll update and save in to the table (clone it back to the database) ->replicate() will clone the modelObject and the ->save() will add it to the database inside the loop !

Thanks Ali

Solution 6:[6]

Use collect function and toJson() will give the output as JSON object which can easily parse.

collect([ 'x' => 3 ])->toJson();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Naveed Sheriffdeen
Solution 2
Solution 3 Virk
Solution 4
Solution 5 Ali Bayati
Solution 6 Usman