如何编写控制器代码以保存复选框中的多个值。
我已经从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>
我需要一个控制器代码来存储学生的检查科目
答案 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