How To Store Multiple Checkbox Value In Database Using Laravel

120

Question: How To Store Multiple Checkbox Value In Database Using Laravel

I'm new with laravel.

How to add subjects based on student id with checkbox form

CREATE FORM

For example, when I select a student with id 3216 and add 2 subjects with id 105 and 106, mysql will create 2 records like this. enter image description here

Here is the code of views

<div class="form-group">     <h9>Student ID</h9>     <div class="col-lg-10">         <select class="form-control" name="student_id[]">             @foreach($student as $stu)                 <option {{ $stu->id }}>{{ $stu->id }}</option>             @endforeach         </select>     </div> </div> <div class="form-group">     <h9>Subject ID</h9>     <div class="col-lg-10">         @foreach($subject as $su)             <input type="checkbox" name="subject_id[]" value="{{ $su->id }}">             <label for="cat_1">{{ $su->id }}</label><br/><br/>         @endforeach     </div> </div> 

Store function:

public function store(Request $request) {     $this->resultRepo->create($request->all());     return redirect()->route('result.index')->with('success', 'Successfully!'); } 

Total Answers: 1

98

Answers 1: of How To Store Multiple Checkbox Value In Database Using Laravel

If you want to store multiple select

  1. Get All selected value in array, in your case it is subject_id[]
$subjectIds = $request->subject_id 

This will be an array

  1. store them as json
$request->merge[     'subject_id' => $subjectIds ? json_encode($subjectIds) : null, ]; 
  1. Store them
$this->resultRepo->create($request->all());  
  1. And When You want to retrieve them
$data = YourModel::findOrFail($id); $subjectIds = json_decode($data->subject_id) dd($subjectIds);