Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hafiz_r's avatar

How to store json data/result into mysql with laravel?

<script>
    var json = {
        "title": "Anxiety Questionnaire",
        "description": "Over the last 2 weeks, how often have you been bothered by any of the following problem?\n\n",
        "completedHtmlOnCondition": [{
            "expression": "({question1}+{question2}+{question3}+{question4}+{question5}+{question6}+{question7}<=4",
            "html": "<h1>Minimal Anxiety <br>You're doing just fine. Take care of yourself little more.</h1>"
        }, {}, {
            "expression": "({question1}+{question2}+{question3}+{question4}+{question5}+{question6}+{question7}<=9 and ({question1}+{question2}+{question3}+{question4}+{question5}+{question6}+{question7}>=5",
            "html": "<h1>Mild Anxiety</h1>"
        }, {
            "expression": "({question1}+{question2}+{question3}+{question4}+{question5}+{question6}+{question7}<=14 and ({question1}+{question2}+{question3}+{question4}+{question5}+{question6}+{question7}>=10",
            "html": "<h1>Moderate Anxiety</h1>"
        }, {
            "expression": "({question1}+{question2}+{question3}+{question4}+{question5}+{question6}+{question7}>=15",
            "html": "<h1>Severe Anxiety <br> <br> You should make an appointment with a counselor as soon as possible.</h1>"
        }],
        "pages": [{
            "name": "page1",
            "elements": [{
                    "type": "rating",
                    "name": "question1",
                    "title": "Feeling nervous or on edge?",
                    "isRequired": true,
                    "rateValues": [{
                        "value": "0",
                        "text": "Not at all"
                    }, {
                        "value": "1",
                        "text": "Several Days"
                    }, {
                        "value": "2",
                        "text": "More than half the days"
                    }, {
                        "value": "3",
                        "text": "Nearly every day"
                    }],
                    "rateMax": 3
                }, {
                    "type": "rating",
                    "name": "question2",
                    "title": "Not being able to stop or control worrying",
                    "isRequired": true,
                    "rateValues": [{
                            "value": "0",
                            "text": "Not at all"
                        }, {
                            "value": "1",
                            "text": "Several Days"
                        },
                        {
                            "value": "2",
                            "text": "More than half the days"
                        }, {
                            "value": "3",
                            "text": "Nearly every day"
                        }
                    ],
                    "rateMax": 3
                }, {
                    "type": "rating",
                    "name": "question3",
                    "title": "Worrying too much about different things",
                    "isRequired": true,
                    "rateValues": [{
                        "value": "0",
                        "text": "Not at all"
                    }, {
                        "value": "1",
                        "text": "Several Days"
                    }, {
                        "value": "2",
                        "text": "More than half the days"
                    }, {
                        "value": "3",
                        "text": "Nearly every day"
                    }],
                    "rateMax": 3
                }, {
                    "type": "rating",
                    "name": "question4",
                    "title": "Trouble relaxing",
                    "isRequired": true,
                    "rateValues": [{
                        "value": "0",
                        "text": "Not at all"
                    }, {
                        "value": "1",
                        "text": "Several Days"
                    }, {
                        "value": "2",
                        "text": "More than half the days"
                    }, {
                        "value": "3",
                        "text": "Nearly every day"
                    }],
                    "rateMax": 3
                },
                {
                    "type": "rating",
                    "name": "question5",
                    "title": "Being so restless that it is hard to sit still",
                    "isRequired": true,
                    "rateValues": [{
                        "value": "0",
                        "text": "Not at all"
                    }, {
                        "value": "1",
                        "text": "Several Days"
                    }, {
                        "value": "2",
                        "text": "More than half the days"
                    }, {
                        "value": "3",
                        "text": "Nearly every day"
                    }],
                    "rateMax": 3
                }, {
                    "type": "rating",
                    "name": "question6",
                    "title": "Becoming easily annoyed or irritable",
                    "isRequired": true,
                    "rateValues": [{
                        "value": "0",
                        "text": "Not at all"
                    }, {
                        "value": "1",
                        "text": "Several Days"
                    }, {
                        "value": "2",
                        "text": "More than half the days"
                    }, {
                        "value": "3",
                        "text": "Nearly every day"
                    }],
                    "rateMax": 3
                }, {
                    "type": "rating",
                    "name": "question7",
                    "title": "Feeling afraid as if something awful might happen",
                    "isRequired": true,
                    "rateValues": [{
                            "value": "0",
                            "text": "Not at all"
                        }, {
                            "value": "1",
                            "text": "Several Days"
                        },
                        {
                            "value": "2",
                            "text": "More than half the days"
                        }, {
                            "value": "3",
                            "text": "Nearly every day"
                        }
                    ],
                    "rateMax": 3
                }
            ]
        }]
    };
    window.survey = new Survey.Model(json);
    survey.onComplete.add(function (result) {
        document.querySelector('#surveyResult').textContent = "Result JSON:\n" + JSON.stringify(result.data,
            null, 3);
    });
    $("#surveyElement1").Survey({
        model: survey
    });

</script>

The result show differently with seven values. Is it possible to total them and save it into a column in database? Thanks

0 likes
30 replies
Martal's avatar

There is a json column type in migrations. You can use it for storing json data.

hafiz_r's avatar

can you tell me how can i total the value? and pass it to table. Does it have to go through a controller? or there is any other way.

jlrdw's avatar

You might consider viewing some of Jefferies free video training.

seen's avatar

depending on how you will retrieve them. if you want them totally you may store them in one column, but if you want them with some relational operations then you may store them in multiple columns.

1 like
hafiz_r's avatar

yeah.. i understand that but i was asking how can i total the result?

Martal's avatar

@hafiz_r

Could not you give us more detailed description of what you want to get? Step by step? There are lots of ways to work with data. Each of them have pros and cons. And the best one can be chosen only by your goal.

hafiz_r's avatar

as you can see from the code. 7 questions gives 7 result as number and 4 result depending on that number. So i want to store the sum of that 7 numeric result/any one of the 4 html result in one column of Authorised user. So how can i do it? or i can do it by passing the value to the controller of the mode that i want to store it to. Thanks

Martal's avatar

Do you want to process your questionnaire on frontend or backend?

Do you want to store only result (e.g. user have Answers array [0,0,1,0,3,0,2], Sum integer 6 and Result string "<h1>Mild Anxiety</h1>". You want to store just Sum and Result string, right?

hafiz_r's avatar

yes. Martal . Exactly

It already shows the result in front end. I just want to store it in database of the user when it generates the result.

Thanks

Martal's avatar

@hafiz_r

So the simplest way is to add result_sum and result_text columns to User model, and make post request on finishing the questionnaire to store the data.

How good are you with Laravel and backend? Do you need detailed guide? Have you watched any Jeffrey's videos?

hafiz_r's avatar

I understand a bit. As far i could do from documentation. Didn't face major problem in storing and retreiving yet. I just don't know which variable stores the result text and if i need to use form or button url to store it. Thanks.

hafiz_r's avatar

anything suitable. As it will update each time the user take the questionnaire. Is js post request suitable?

Martal's avatar

So your questionnaire is available only for authenticated users, not for guests? And your user can pass this questionnaire many times, right? Do you want to store only one result per user or all of them to see statistics in time?

hafiz_r's avatar

Available only to auth user. One result per user.

Martal's avatar

So a user can update questionnaire and you want to store only the last result?

Martal's avatar

Ok, give me half an hour I'll try to describe your controller and blades.

Martal's avatar

routes/web.php

Route::group(['middleware' => 'auth'], function () {
    Route::get('questionnaire', 'QuestionnaireController@show');
    Route::match(
        ['put',' patch'],
        'questionnaire',
        'QuestionnaireController@update'
    );
});

app/Http/Controllers/QuestionnaireController.php

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class QuestionnaireController extends Controller
{
    /**
     * Display the specified resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {
        $user = $request->user();

        return view('questionnaire', compact('user'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $user = $request->user();

        $user->update($request->only([
            'quest_result_sum', 'quest_result_text'
        ]));

        return view('questionnaire', compact('user'));
    }
}

users migration schema

Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();

    $table->integer('quest_result_sum')->nullable();
    $table->string('quest_result_text')->nullable();
});

blades is on the way (=

Martal's avatar

resources/questionnaire.blade.php, patch request part

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("PATCH", "/questionnaire");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({quest_result_sum:3, quest_result_text:"<h1>SomeText</h1>"}));

I assume that you can make frontend of your questionnaire. (Actually I am rather bad in frontend. (= )

hafiz_r's avatar

request part i didn't undersatnd. The variable you gave is predefined right? eg.quest_result_text

hafiz_r's avatar

web.php

oute::group(['middleware' => 'auth:student'], function () {
    Route::view('/student', 'student');
    Route::get('student/profile', ['uses' => 'ProfilesController@indexStudent', 'as' => 'student.profile']);
    Route::post('student/profile/update', ['uses' => 'ProfilesController@updateStudent', 'as' => 'student.profile.update']);
    Route::resource('appointments', 'AppointmentsController');
    Route::get('/createAppointment', 'AppointmentsController@create');
    Route::get('/chat', 'ChatController@index')->name('chat');
    Route::post('pusher/auth', function () {
        return auth()->user();
    });
    Route::match(
        ['put', ' patch'],
        'student',
        'ProfilesController@updateD'
    );
});

ProfilesController.php

 public function updateD(Request $request, User $user)
    {
        $user = $request->user();

        $user->update($request->only([
            'quest_result_text'
        ]));

        return view('student', compact('user'));
    }

student.blade.php (survey included in modal)

 <div class="modal-body">
                @include('inc.anxietySurvey')
            </div>
            {{-- <div class="modal-footer" >
        <button type="button" class="btn btn-secondary" data-dismiss="modal" >Close</button>

Database

 $table->integer('contact')->nullable();
            $table->string('about')->nullable();
            $table->string('avatar')->default('default.jpg');
            $table->string('depression')->nullable();
            $table->string('anxiety')->nullable();
Martal's avatar

I assumed that you have you questionnaire made with js. User choses his answers, clicks button (e.g. "Finish"), after that you intercept an onclick button event and send data in handler.

Martal's avatar

@hafiz_r

Sorry, no User $user argument should be in your updateD controller function. I have made an error. Only Request $request argument should be there.

hafiz_r's avatar

That's the problem @martal as i gave you the code of survey above. It's a js library called survey js. So i don't have an onclick in the code. I guess it's in the linked js file. This is the whole code of my survey file which is depressionSurvey.blade.php

<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/jquery"></script>
<script src="https://surveyjs.azureedge.net/1.1.8/survey.jquery.js"></script>
<link href="https://surveyjs.azureedge.net/1.1.8/survey.css" type="text/css" rel="stylesheet" />



<div id="surveyElement"></div>
<div id="surveyResult"></div>

Martal's avatar

@hafiz_r

In step 5 there is a sendDataToServer callback. Send data in it.

function sendDataToServer(survey) {
  // var resultAsString = JSON.stringify(survey.data);
  var quest_result_sum =  3;//take data from survey var
  var quest_result_text = "<h1>SomeText</h1>";//take data from survey var
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("PATCH", "/questionnaire");
  xmlhttp.setRequestHeader("Content-Type", "application/json");
  xmlhttp.send(JSON.stringify({quest_result_sum:quest_result_sum, quest_result_text:quest_result_text}));
}

hafiz_r's avatar

hey @martal

window.survey = new Survey.Model(json);
    survey.onComplete.add(function (result) {
        document.querySelector('#surveyResult').textContent = "Result JSON:\n" + JSON.stringify(result.data,
            null, 3);
    });
    $("#surveyElement").Survey({
        model: survey,
        onComplete: sendDataToServer
    });

    function sendDataToServer(survey) {
        // var resultAsString = JSON.stringify(survey.data);
        var quest_result_sum = 3; //take data from survey var
        var quest_result_text = result.data; //take data from survey var
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("PATCH", "/student");
        xmlhttp.setRequestHeader("Content-Type", "application/json");
        xmlhttp.send(JSON.stringify({
            quest_result_sum: quest_result_sum,
            quest_result_text: quest_result_text
        }));

i tired to store the the result.data in result_text. It's not working and how can i set the result_text to the html text below

var json = {
        "title": "Depression Questionnaire",
        "description": "Over the last 2 weeks, how often have you been bothered by any of the following problem?\n\n",
        "completedHtmlOnCondition": [{
            "expression": "({question1}+{question2}+{question3}+{question4}+{question5}+{question6}+{question7}+{question8}+{question9}<=4",
            "html": "<h1>Minimal Depression<h1> "
Martal's avatar

@hafiz_r

Please, show what is in survey.data in sendDataToServer function.

hafiz_r's avatar

I have tried this :(

function sendDataToServer(survey) {
        // var resultAsString = JSON.stringify(survey.data);
        var quest_result_sum = 3; //take data from survey var
        var quest_result_text = JSON.stringify(survey.data) //take data from survey var
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("PATCH", "/student");
        xmlhttp.setRequestHeader("Content-Type", "application/json");
        xmlhttp.send(JSON.stringify({
            quest_result_sum: quest_result_sum,
            quest_result_text: quest_result_text
        }));
Martal's avatar

@hafiz_r

I cannot see you monitor so I cannot know what is the error. Is it 404 error? Misprint in controller? Mysql error? What kind of error do you have? What works and what not?

Please or to participate in this conversation.