Skip to content
Advertisement

how to get nth row in foreach loop in laravel blade?

consider i have 2 table like this

remaining | c_remaining

0 | 10

20 | 30

40 | 50

i want 10 – 20 , 30 – 40 and 50 – 0 and i want it in foreach loop

@foreach($paid_amounts as $pay_amount)
              <tr>
                <td>{{ $pay_amount->c_remaining - $pay_amount->remaining[select 2nd value] }}</td>
              </tr>
              @endforeach

how i can how i can skip first value and get value from next from current 1?

Advertisement

Answer

You can try to shape the data in the controller itself.

$paid_amounts->map(function($item, $key) use($paid_amounts) {

    $remaining = isset($paid_amounts[$key + 1]) 
        ? $paid_amounts[$key + 1]->remaining 
        : $paid_amounts[0]->remaining;
    
    //Add a new property to each element of the collection
    $item->prop = $item->c_remaining - $remaining;

    return $item;
});

Then in the blade view you can use the new property

@foreach($paid_amounts as $pay_amount)
    <tr>
        <td>{{ $pay_amount->prop }}</td>
    </tr>
@endforeach
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement