首页 > 解决方案 > 在 Laravel 中为新行添加 div 行

问题描述

我是 Laravel 的初学者。我在 Laravel 8 中制作我的项目。

我有这个代码:

@foreach($productIngredients as $productIngredient)
@php
    if($selectedProductIngredients->contains('ingredient_id', $productIngredient->id) === true){
        $item = \App\Models\SelectedProductIngredient::where('product_id', $product->id)->where('ingredient_id', $productIngredient->id)->first();
        $weight = $item->weight;
    } else {
        $weight = null;
    }
@endphp

<div class="col-6">
    <div class="form-check py-2">
        <input id="productIngredientId-{{ $productIngredient->id }}"
               class="form-check-input enableInput" style="margin-top:10px"
               name="productIngredient[]" type="checkbox"
               value="{{ $productIngredient->id }}"
               @if($selectedProductIngredients->contains('ingredient_id', $productIngredient->id) === true) checked @endif>
        <label class="form-check-label" for="flexCheckChecked">
            {{ $productIngredient->name }} [{{ $productIngredient->short_name }}]
        </label>
        <input id="productIngredient-{{ $productIngredient->id }}" type="text"
               name="productIngredient-{{ $productIngredient->id }}" maxlength="10"
               class="form-control weight-input weightMask"
               style="width:100px;display: inline; margin-left:20px" placeholder=""
               value="{{ $weight }}">
    </div>
</div>
@endforeach

它工作正常。

我希望 1 行中有 2 条记录。所以我想在最后一条记录的情况下添加并关闭 div

我怎样才能做到这一点?

请帮我。

标签: phplaravel

解决方案


你知道Laravel 的集合吗?它可以帮助你。

您可以使用chunk方法,它将集合分成多个给定大小的较小集合:

@foreach($productIngredients->chunk(2) as $chunk)
  <div class="row">
  @foreach($chunk as $productIngredients)
    <div class="col-6">
      ...
    </div>
  @endforeach
  </div>
@endforeach

推荐阅读