我面临一个问题,即所有复选框均已选中。我只希望选中在数据库中具有值的复选框。
I have these three tables where place_category is the pivot table
------- -------------- ----------
places place_category categories
------ -------------- ----------
id place_id id
name category_id name
eloquent relationships are set.
Here I'm trying to associate many categories for one place but I want only the categories that I added to that place to be checked in the checkbox.
...........
@foreach($categories as $category)
<div class="col-lg-3">
<div class="form-group">
<input type="checkbox" name="category[]" value="{{$category->id}}" {{isset($category) ? 'checked': '' }} >{{ $category->name }}<br>
</div>
</div>
@endforeach
我的病情有问题吗?{{isset($ category)吗?'已检查':”}}
问题是您$category
将始终以这种方式设置,它将始终返回true。
您可能正在遍历所有类别,因此您需要将类别与产品或视图中的任何产品进行比较,并检查类别ID是否是为该产品选择的类别ID。如下所示:
@foreach($categories as $category)
<div class="col-lg-3">
<div class="form-group">
<input type="checkbox" name="category[]"
value="{{$category->id}}"
@if($category->id === $model->category_id) 'checked' @endif>
{{ $category->name }}<br>
</div>
</div>
@endforeach
现在,此代码仅在将类别附加到要列出的模型时才检查类别。如果这对您来说还不够,请从控制器显示更多代码,并从视图中获得更好的帮助。
-编辑
根据您的编辑,您正在那里使用多对多关系..这样就可以做到:
@if($place->categories->contains($category->id)) 'checked' @endif
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句