Cha*_*ara 5 php checkbox laravel
我是 Laravel 的新手。我使用循环将一些复选框值保存到数据库中,但它只将数组中的最后一个值保存到数据库中。
这是我的表格
<form action="{{url('resortf')}}" method="post" enctype="multipart/form-data">
<input hidden name="h_id" value="{{ $hotel->id}}">
@foreach($facility as $facilities)
<div class="col-md-4">
<img src="{{$facilities->image}}" width="50px" height="50px;">
<label>{{$facilities->name}}</label>
<input type="checkbox" value="{{$facilities->id}}" name="facilities[]">
</div>
@endforeach
<div class="row">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-success" value="Next">
<input type="reset" class="btn btn-success" value="Reset">
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
形式工作正常;$facilities并$hotel从控制器传递。
这是商店功能
public function store(Request $request) {
$resortfacility = new Resortfacility;
$loop = $request->get('facilities');
foreach ($loop as $value){
$resortfacility->h_id = $request->get('h_id');
$resortfacility->f_id = $value;
$resortfacility->save();
}
}
Run Code Online (Sandbox Code Playgroud)
还有其他可行的方法吗?
出现问题的原因是您创建了一个实例Resortfacility,然后填写了它的值并保存。问题是,每次在循环中对此对象执行更改时,您都是updating现有对象,这就是为什么数据库中只有一条记录,即循环中的最后一条记录。
尝试在循环内创建 Resortfacility 的新实例,如下所示:
public function store(Request $request) {
$loop = $request->get('facilities');
foreach ($loop as $value){
$resortfacility = new Resortfacility;
$resortfacility->h_id = $request->get('h_id');
$resortfacility->f_id = $value;
$resortfacility->save();
}
}
Run Code Online (Sandbox Code Playgroud)