Akshay Kumar
Akshay Kumar

Reputation: 7660

how can we define a loop variable for foreach loop in laravel php blade tempalte

I tried this but it got printed in fronted

{{ $x=1}}
@if(count($bookings))
    @foreach ($bookings as $data)
        <tr>
            <td>{!! $x !!}</td>
            <td>{!! $data->service->id !!}</td>
            <td>{!! $data->service->title !!}</td>
            <td>{!! $data->full_name !!}</td>
            <td>{!! $data->email !!}</td>
            <td>{!! $data->phone !!}</td>
            <td>{!! date('d-m-Y', strtotime($data->booking_date))  !!} {!! $data->slot_start_from !!}</td>
        {{$x++}}
    @endforeach

This code not working value of x got printed . i don't want to use code php code here any good suggestion welcome

Upvotes: 0

Views: 1905

Answers (2)

N69S
N69S

Reputation: 17206

As @RomanBobrik said, use the loop variable $loop to get the iteration

    @foreach ($bookings as $data)
        <tr>
            <td>{{ $loop->iteration }}</td>
            <td>{{ $data->service->id }}</td>
            <td>{!! $data->service->title !!}</td>
            <td>{!! $data->full_name !!}</td>
            <td>{{ $data->email }}</td>
            <td>{!! $data->phone !!}</td>
            <td>{!! date('d-m-Y', strtotime($data->booking_date))  !!} {!! $data->slot_start_from !!}</td>

    @endforeach

Upvotes: 3

Roman Meyer
Roman Meyer

Reputation: 2872

You're looking for loop variable, which exists in Laravel Blade.

https://laravel.com/docs/5.8/blade#the-loop-variable

So, just use:

<td>{!! $loop->index !!}</td>

If you have Laravel 5.2 and lower, there is no loop variables. In that case you can use @php shortcut

@php $x=1 @endphp
...
<td>{!! $x++ !!}</td>

Upvotes: 1

Related Questions