Paul Caleb
Paul Caleb

Reputation: 205

what is a good way to save an array data to mySQL in laravel

enter image description here

Its an online result marker. Once the user clicks save it gets the CA(Continious assessment) and it gets the Exam marks and the teachers remark for the particular student. I want to know how i can insert these fields into my database the right way.

return $request->all();

the above code returns the image below enter image description here

Upvotes: 1

Views: 561

Answers (1)

mbozwood
mbozwood

Reputation: 1402

$i = 0;
foreach($request->id as $id) {
    $model = new Model;
    $model->user_id = $id;
    $model->ca_mark = $request->ca_mark[$i];
    $model->exam_mark = $request->ca_mark[$i];
    $model->remarks = $request->remarks[$i];
    $model->save();
    $i++;
}

Query Builder

$i = 0;
foreach($request->id as $id) {
    DB::table('table')->insert([
        'user_id' => $id, 
        'ca_mark' => $request->ca_mark[$i],
        'exam_mark' => $request->ca_mark[$i],
        'remarks' => $request->remarks[$i]
    ]);
    $i++;
}

The above code has been written based on an assumption of the database table structure. In short, foreach on the ID's as this would be the student ID, and take the ca_mark, exam_mark and remark based on the key of the id.

Upvotes: 2

Related Questions