eons
eons

Reputation: 456

how do i save a group of checkboxes

How to write controller code to save multiple values from checkboxes.

i have retrieve the student and subjects as can be seen from StudentController@show, i want to register a couple of subject per student

StudentController@show to get the student and subjects

 function show($id)
  {
    $targetStudent = $this->studentRepository->findStudentById($id);

    $subjects = Subject::all();

    $this->setPageTitle('Students', ' Student : 
           '.$targetStudent->student_name);

    return view('admin.students.show', 
   compact('targetStudent','subjects'));
}

this is show.blade.php

  <form action="{{ route('admin.registrations.store') }}" method="POST">
                      @csrf
                        @foreach($subjects as $subject)
                                <tr>
                                    <td>{{ $subject->id }}</td>
                                    <td>{{ $subject->subject_code }}</td>
                                    <td>{{ $subject->subject_name }}</td>
                                    <td>{{ $subject->credit_hours }}</td>

                                    <td class="text-center">
                                        <div class="form-group">
                                            <div class="form-check">
                                              <label class="form-check-label">
                                              <input class="form-check-input" name="subject[{{$subject->id}}]" value="{{$subject->subject_code}}" type="checkbox">
                                              </label>
                                            </div>
                                          </div>
                                    </td>
                                </tr>
                        @endforeach
                    </tbody>
                </table>
              </div>

          <!-- modal footer-->
              <div class="modal-footer">
                      <button class="btn btn-secondary" data-dismiss="modal">Close</button>
                      <button type="submit" class="btn btn-primary">Register Subjects</button>
              </div>
            </form>

i need a controller code to store checked subjects for the student

Upvotes: 0

Views: 78

Answers (1)

kirubha
kirubha

Reputation: 133

Let's try this to save group of checkbox.

<input class="form-check-input" name="subject[{{$subject->id}}]" value="{{$subject->subject_code}}" type="checkbox">

In your save controller :

  $modal                    = new your_modal();
  $modal->your_column_name  = serialize(($request->name));
  $modal->save();

While retrieving, use unserialize.

Documentation of serialize is here:https://www.php.net/manual/en/function.serialize.php

Documentation of unserialize is here:https://www.php.net/manual/en/function.unserialize.php

Upvotes: 1

Related Questions