Laravel provides simple blade template which provides many directive to use direct in html code. With blade engine you can write core PHP code with @php
directive. In Blade, you can also use loop directive like @for
, @foreach
, @forelse
and @while
instead of loop condition. While looping, you may use $loop
variable for valuable information.
In this article, we will show $loop
variable and its properties to get many useful information.
If you want to check whether it is first or last iteration of the loop, then you may use this.
@php
$numbers = [3, 2, 8, 12, 2, 6];
@endphp
@foreach ($numbers as $number)
@if ($loop->first)
{{ $number }} {{-- 3 --}}
@endif
@if ($loop->last)
{{ $number }} {{-- 6 --}}
@endif
@endforeach
You may get the index of the loop, which starts from 0.
@php
$numbers = [3, 2, 8, 12, 2, 6];
@endphp
@foreach ($numbers as $number)
@if ($loop->index == 2)
{{ $number }} {{-- 8 --}}
@endif
@endforeach
or the iteration of the loop, which starts from 1.
@php
$numbers = [3, 2, 8, 12, 2, 6];
@endphp
@foreach ($numbers as $number)
@if ($loop->iteration == 3)
{{ $number }} {{-- 8 --}}
@endif
@endforeach
If you want to get remaining iterations of the loop, you may use.
@php
$numbers = [3, 2, 8, 12, 2, 6];
@endphp
@foreach ($numbers as $number)
@if ($loop->iteration == 1)
{{ $loop->remaining }} {{-- 5 --}}
@endif
@endforeach
You may use count property to get total number of items in the array.
@php
$numbers = [3];
@endphp
@foreach ($numbers as $number)
{{ $loop->count }}
@endforeach
Same way you may find whether the current iteration is even or odd.
@php
$numbers = [3, 2, 8, 12, 2, 6];
@endphp
@foreach ($numbers as $number)
@if ($loop->even)
{{ $number }}
@endif
@endforeach
If you are iterating loop within loop, you may get the depth of the loop.
@foreach ($users as $user)
@foreach ($user['articles'] as $article)
{{ $loop->depth }}
@endforeach
@endforeach
While looping internal loop, you may get parent loop details with parent property.
@foreach ($users as $user)
@foreach ($user['articles'] as $article)
{{ $loop->parent->iteration }}
@endforeach
@endforeach
I hope it will help you.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Laravel 7 Guzzle Http Client Request Example
Hello Artisan, in this tutorial i am goi...Build Dynamic Data Table in Vue.js 2+ with Vuetify
In this tutorial, we are going to learn...Laravel 8 - Auto Load More Data on Page Scroll with AJAX with Example
Hello Dev. This detailed article, wil...John the Ripper Installation and Crack Password
John the Ripper is a free, most pop...Start Applications Automatically on Login in Ubuntu
Many of us need to open certain applicat...