拉拉维尔表单复选框数据



我有两个表;两个表都有几列。在一个中,我拥有用户可以选择的所有许可证(带有复选框(,在另一个中,我存储用户拥有的许可证。

我创建了一个模型来获取所有许可证,并创建了一个模型来获取用户拥有的许可证。

现在,我不明白如何在用户已经拥有的许可证中创建所有许可证的视图 - 例如,当我使用这些复选框创建表单时,如何检查用户是否已经拥有许可证。

我可以获取值,但我无法获得@if语法工作。

这是我目前的代码:

<div class="form-group col-sm-12">
<div class="form-check form-check-inline">
@foreach($all_license as $all_licen_row)
@foreach($drive_licenses as $lisen)
@if($lisen->license_id==$all_licen_row->id)
<input class="form-check-input" type="checkbox"
name="{{$all_licen_row->license_id}}" checked>
<label class="form-check-label"
for="inlineCheckbox1">{{ $all_licen_row->class }}</label>)
@else
<input class="form-check-input" type="checkbox" name="{{$all_licen_row->license_id}}">
<label class="form-check-label"
for="inlineCheckbox1">{{ $all_licen_row->class }}</label>)
@endif
@endforeach
@if($errors->has('id'))
<span class="help-block">
<strong class="text-danger">{{ $errors->first('drive_licence') }}</strong>
</span>
@endif
@endforeach
</div>
</div>

这样的事情通常更容易处理,而无需使用内部循环。您可以在循环$all_license之前检查应该选择哪个 id,只需将drive_licenses中的 id 存储到数组中,只需检查数组中是否存在$all_licenseid。例:

<?php 
$ids = array();
foreach($drive_licenses as $lisen) {
array_push($ids, $lisen->license_id)
}
?>
@foreach($all_license as $all_licen_row)
@if(in_array($all_licen_row->id, $ids))
<input class="form-check-input" type="checkbox" name="{{$all_licen_row->license_id}}" checked>
<label class="form-check-label" for="inlineCheckbox1">{{ $all_licen_row->class }}</label>
@else
...
@endif
@endforeach

如果需要,您还可以使用三元运算符(例如,(?:)(来缩短一些代码。例:

@foreach($all_license as $all_licen_row)
<input class="form-check-input" type="checkbox" name="{{$all_licen_row->license_id}}"{{ (in_array($all_licen_row->id, $ids) ? ' checked' : '') }}>
<label class="form-check-label" for="inlineCheckbox1">{{ $all_licen_row->class }}</label>
@endforeach

最新更新