我如何保存一组复选框

时间:2019-09-06 02:49:01

标签: laravel

如何编写控制器代码以保存复选框中的多个值。

我已经从StudentController@show中检索到了学生和科目,我想为每个学生注册几个科目

StudentController@show获取学生和科目

 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'));
}

这是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>

我需要一个控制器代码来存储学生的检查科目

1 个答案:

答案 0 :(得分:1)

让我们尝试保存复选框组。

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

在您的保存控制器中:

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

检索时,请使用反序列化。

序列化的文档在这里:https://www.php.net/manual/en/function.serialize.php

反序列化的文档在这里:https://www.php.net/manual/en/function.unserialize.php