Laravel Blade Loop Helpers

Hello Guys,
Today we will learn about the loop variable in the laravel blade. In PHP sometime we need to get the first, last, current index, count, etc in the loop. For these values, developers write multiple lines of code. 
But in the laravel blade, we can use the laravel $loop variable in the loop. 


The Loop Variable

While iterating through a foreach loop, a $loop the variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop:

Example: In this example, we will get the first and  last iteration

@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @if ($loop->last)
        This is the last iteration.
    This is user {{ $user->id }}



If you are using a nested loop then we may access the parent loop's $loop variable via the parent property:

@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            This is the first iteration of the parent loop.

The $loop variable also contains a variety of other useful properties: 
I will try to explain every property of the $loop variable.


$loop->index :  The index of the current loop iteration (starts at 0).


$loop->iteration  :  The current loop iteration (starts at 1).


$loop->remaining: The iterations remaining in the loop.


$loop->count:  The total number of items in the array being iterated.


$loop->first: Whether this is the first iteration through the loop.


$loop->last:  Whether this is the last iteration through the loop.


$loop->even:  Whether this is an even iteration through the loop.


$loop->odd:  Whether this is an odd iteration through the loop.


$loop->depth:  The nesting level of the current loop.


$loop->parent:  When in a nested loop, the parent's loop variable.

These are the list of $loop properties. Hope they will help you with your code. 

If I am missing any property. then please let me know via comment.
You can also share this post with your friends.