Martney Acha
Martney Acha

Reputation: 3002

Laravel Foreach Looping

I need to display the previous value of the iterated array, here is code

<tr>
    <th></th>
    <th>Customer ID</th>
    <th>Customer Name</th>
    <th>Delivery Address</th>
    <th>Contact No.</th>
    <th>Zip Code</th>
    <th>Payment Terms</th>
    <th>Credit Limit</th>
</tr>
<?php $previousValue = null; ?>
@foreach($customer_count as $key => $value)
    <tr>
        <td>{{$previousValue=$value->customer_name }}</td>
        <td>{{ $value->id }}</td>
        <td>{{ $value->customer_name }}</td>
        <td>{{ $value->delivery_address }}</td>
        <td>{{ $value->contact_number }}</td>
        <td>{{ $value->area_id }}</td>
        <td>{{ $value->payment_term_id }}</td>
        <td>{{ $value->credit_limit }}</td>
    </tr>
@endforeach

I need to display the previous name of Customer in the iteration? Any idea on how to do this?

Upvotes: 1

Views: 329

Answers (4)

DsRaj
DsRaj

Reputation: 2328

At very first set the previous value as blank and then at the bottom set value in $previousValue

<?php $previousValue = '';?>
@foreach($customer_count as $key => $value)
    <tr>
        <td>{{ $previousValue }}</td>
        <td>{{ $value->id }}</td>
        <td>{{ $value->customer_name }}</td>
        <td>{{ $value->delivery_address }}</td>
        <td>{{ $value->contact_number }}</td>
        <td>{{ $value->area_id }}</td>
        <td>{{ $value->payment_term_id }}</td>
        <td>{{ $value->credit_limit }}</td>
    </tr>
    <?php $previousValue = $value->customer_name; ?>
@endforeach

Upvotes: 0

Niklesh Raut
Niklesh Raut

Reputation: 34914

Set value at the end , I set blank for first

 @foreach($customer_count as $key => $value)
      <tr>
           <td>{{$previousValue or ""}}</td>
           .....
           .....
      </tr>
      <?php $previousValue = $value->customer_name ?>
  @endforeach

Upvotes: 2

Tai Le
Tai Le

Reputation: 493

please try this

<td>{{ (!$loop->first) ? $customer_count[$key - 1]->customer_name : '' }}</td>

You can read more about foreach loop here.

Upvotes: 0

parker_codes
parker_codes

Reputation: 3397

$customer_count[$key - 1]

Of course you'll need to check if that exists or use the null-coalesce operator or something, so:

@php

$previous = $customer_count[$key - 1] ?? false;

@endphp

Then use:

@if( $previous ) 
... some stuff ...
@endif

wherever you need to inject.

Upvotes: 0

Related Questions