首页 > 解决方案 > 需要帮助使用 @foreach 和关系模型将数组值显示到刀片中

问题描述

我有 4 种订阅类型(每月、3 个月、6 个月和每年)。我成功插入了与我的产品模型相关的值。现在我需要进行更新。场景是用户一开始只选择两个订阅计划,然后决定添加更多订阅。在我的编辑中它只显示用户选择的内容。

 @foreach($product->subscriptions as $subscription)

 <input class="form-check-input" name="availability[]" type="checkbox" value="{{ $row->id }}" checked>
 <label class="form-check-label" for="materialUnchecked"><b>{{ $subscription->name }}</b></label>

 <input type="text" name="price[]" value="{{ $subscription->pivot->price }}">

 @endforeach

这将给出结果:我怎样才能显示之前未选择的其他选项。 在此处输入图像描述

如果结果小于 4,我想显示未选中的其余订阅可用性。例如,用户仅选择每月和每年。现在在我的编辑视图中,我还想显示另外两个(3 个月和 6 个月选项),以防他们想添加一些东西。怎么做?

标签: arrayslaravelcheckboxforeachrelation

解决方案


 @foreach($subscriptions as $subscription)

   <input class="form-check-input" name="availability[]" type="checkbox" value="{{ $row->id }}" {{in_array($subscription->id, $product->subscriptions->pluck('id')) ? 'checked' : ''}}>
   <label class="form-check-label" for="materialUnchecked"><b>{{ $subscription->name }}</b></label>

   <input type="text" name="price[]" value="{{ $subscription->pivot->price }}">

 @endforeach

推荐阅读