Brij Sharma
Brij Sharma

Reputation: 371

How to store JSON data array database if this data come from API in Laravel?

I am working on online examination system on laravel when users get exam I want to receive some data from API and store in a database. Data will be something like this.

{
    "user_id": [
        "420"
    ],
    "test_id": [
        "12"
    ],
    "question_id": [
        "1",
        "2",
        "3",
        "4"
    ]
}

My Controller

$fbres       = new Testapp;
$json        = $request->all();
$data        = $json;

$user_id     = $request->user_id;
$question_id = $request->question_id;
$test_id     = $request->test_id;

foreach ($data as $key)
{
    $user_id     = $key['user_id'];
    $test_id     = $key['test_id'];
    $question_id = $key['question_id'];

    $data1 = array(
        array('user_id'=> $user_id, 'question_id'=> $question_id, 'test_id'=> $test_id)
    );

    $fbres::insert($data1);
}

Upvotes: 2

Views: 1368

Answers (2)

faizan.sh
faizan.sh

Reputation: 537

Convert arrays to json string using json_encode function and then store it

$fbres = new Testapp;
$json = $request->all();
$data = $json;

$data = $request->ques;

$user_id = $request->user_id;
$question_id = $request->question_id;
$test_id     = $request->test_id;

 $data1 = array(
        array('user_id'=> json_encode($user_id), 'question_id'=> json_encode($question_id), 'test_id'=> json_encode($test_id))
    );
    $fbres::insert($data1);

Upvotes: 0

amku91
amku91

Reputation: 1038

Encode the array using json_encode() php method. and no need to call insert into loop. It's time consuming and may blast your DB.

$fbres       = new Testapp;
$json        = $request->all();
$data        = $json;
$data        = $request->ques;
$user_id     = $request->user_id;
$question_id = $request->question_id;
$test_id     = $request->test_id;

$finalData = array();
$blankArr = array();
//Check for array 1-d or 2-d
if(isset($data["user_id"])){
  array_push($blankArr, $data);
}else{
 $blankArr = $data;
}
foreach ($blankArr as $key => $value)
{
    $usr_id     = $value['user_id']['0'];
    $test_id     = $value['test_id']['0'];
    foreach($value['question_id'] as $k => $v){
         $finalData = array('user_id'=> $usr_id, 'question_id'=> $v, 'test_id'=> $test_id);

         $fbres::insert($finalData);
    } 
}

Hope it will help you.

Upvotes: 1

Related Questions