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]
Import and Export Excel file in Laravel 7
import export excel or CSV from a databa...How to show and hide dropdown menu on mouse hover using CSS
Use the CSS :hoverpseudo-class If you...How to Preview an Image Before it is Uploaded Using jQuery
Use the JS readAsDataURL() Method You...How to install elastic search in local system and live server
Laravelcode write one of the very helpfu...How to Detect Browser Window is Active or not
Javascript is great programming language...