Adnan Mujkanovic Adnan Mujkanovic - 11 months ago 40
HTML Question

foreach with every 10th and 2nd changes

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('')->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

Answer Source

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">
                {{-- Create chunks of 2 so every row is filled with up to 2 coupons --}}
                @foreach($pageCoupons->chunk(2) as $rowCoupons)
                    {{-- Loop over the row coupons to create the columns --}}
                    @foreach($rowCoupons as $coupon)
                        <span class="coupon">{{ $coupon->code }}</span><br>
                        <span class="name">{{ $coupon->user->name }}</span>