简体   繁体   中英

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM