每10次和第2次更改

So i am dealing with coupons that I need to print. I prepared the view and I am passing coupons to the view:

public function printSelected($ids){
        $couponIDs = explode(',', $ids);
        $selectedCoupons = Coupon::find($couponIDs);

        return view('admin.coupons.print')->with(compact('selectedCoupons'));
    }

Now I need to loop through them in a certain manner.

  1. every 10 coupons I need a new "page" block because 10 coupons fit into a page block

  2. every second coupon I need a new table row because 2 coupons or table data fits into one row

enter image description here

There are multiple ways to do this but I find it very readable to use the chunk method of the Collection object. Another option would be to use modulus ($index % 10 === 0).

<div class="coupons">
    {{-- Create chunks of 10 as this is the max per page --}}
    @foreach($selectedCoupons->chunk(10) as $pageCoupons)
    <div class="page">
        <div class="subpage">
            <table>
                {{-- Create chunks of 2 so every row is filled with up to 2 coupons --}}
                @foreach($pageCoupons->chunk(2) as $rowCoupons)
                <tr>
                    {{-- Loop over the row coupons to create the columns --}}
                    @foreach($rowCoupons as $coupon)
                    <td>
                        <span class="coupon">{{ $coupon->code }}</span><br>
                        <hr>
                        <span class="name">{{ $coupon->user->name }}</span>
                    </td>
                    @endforeach
                </tr>
                @endforeach
            </table>
        </div>
    </div>
    @endforeach
</div>

You can use the collection's chunk method to loop over chunks of your coupons:

<div class="coupons">
    @foreach ($selectedCoupons->chunk(10) as $page)
    <div class="page">
        <div class="subpage">
            <table>
                @foreach ($page->chunk(2) as $row)
                <tr>
                    @foreach ($row as $coupon)
                    <td>
                        <span class="coupon">{{ $coupon->code }}</span><br>
                        <hr>
                        <span class="name">{{ $coupon->user->name }}</span>
                    </td>
                    @endforeach
                </tr>
                @endforeach
            </table>
        </div>
    </div>
    @endforeach
</div>