Home > database >  How to save multiple records in Laravel
How to save multiple records in Laravel

Time:07-28

To save 1 data is like this. Should I loop the ->save(); part so I can make 2 or more different columns for each record?

$rec = new Record;

$rec->record_id = $id; // multiple ids
$rec->record_name = $name // multiple names

$rec->save();

CodePudding user response:

$rec = [
    ['record_id'=>$id, 'record_name'=>$name],
    ['record_id'=>$id2, 'record_name'=>$name2],
    //...
];

Record::insert($rec);

Same Question

CodePudding user response:

public function store(Request $request)
{
    $data = $request->all();
    $mark = new Record();
    $mark->out_of = $data['out_of'];
    if ($data['student_id']) {
        foreach ($data['student_id'] as $row => $value) {
            $data1 = array(
                'out_of' => $mark->out_of,
                'student_id' => $data['student_id'][$row],
                'guardian_id' => $data['guardian_id'][$row],
                'marks_obtained' => $data['marks_obtained'][$row],
                'comment' => $data['comment'][$row],
            );
            Record::create($data1);
        }
    }
    return redirect('/home')->with('success', 'Record Added Successfully');
}

in your view

<form action="/record/store" method="post">
  @csrf
   <input type="text" name="student_id">
   <input type="text" name="guardian_id[]">
   <input type="text" name="marks_obtained[]">
   <input type="text" name="out_of">
   <input type="text" name="comment[]">
   <button type="submit">Post</button>

</form>
  • Related