Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture the value of previous iteration in a loop Laravel PHP

I have a foreach iteration with this variable:

$cart = Cart {#167 ▼

  +lines: array:2 [▼
    0 => CartLine {#168 ▼
      +cart_line_id: 989642
      +cart_id: 13049301
      +parent_line_id: null
      +quantity: 1
      +article_id: 1164
      +article_name: "CUSTOMIZED T-SHIRT"
      +pvp: 29.5
    }
    1 => CartLine {#170 ▼
      +cart_line_id: 989643
      +cart_id: 13049301
      +parent_line_id: 989642
      +quantity: 2
      +article_id: 199
      +article_name: "EXTRA COMPLEMENT"
      +pvp: 2.5

    }
  ]

}

And this is my laravel foreach loop:

@foreach ($cart->lines as $line)

@endforeach

I want this:

@foreach ($cart->lines as $line)
   @if($line->parent_line_id == $line->cart_line_id(previous))
     //print extra
   @endif
@endforeach

I want get the previous item of the current item iteration.

This is possible?

like image 549
RichardMiracles Avatar asked Sep 06 '25 23:09

RichardMiracles


1 Answers

Like this:

@foreach ($cart->lines as $index => $line)
   @if($index > 0 && $line->parent_line_id == $cart->lines[$index - 1]->cart_line_id)
     //print extra
   @endif
@endforeach

Or using $loop variable (seeing you're using 5.3):

@foreach ($cart->lines as $line)
   @if(!$loop->first && $line->parent_line_id == $cart->lines[$loop->index - 1]->cart_line_id)
     //print extra
   @endif
@endforeach
like image 53
DevK Avatar answered Sep 08 '25 13:09

DevK