$loop variable in foreach loop in laravel


We have already written several tutorials for directive’s. If you are not following please go through the links as well things to know in laravel : chapter three , creating your own custom blade directive .We already know how powerful laravel blade template engine and it’s directives are. If we are using laravel default blade template engine, than we do know what @foreach, @forelse, @if and other many more directive’s. We use them day to day.

Today, we are going deeper into one of the directive name @foreach . As we already know this one is amazing but have you heard about $loop variable that is available inside this loop.


@foreach is laravel directive that we can use same way as we used to use foreach in PHP.

@foreach is more powerful than a normal PHP foreach loop. $loop variable is one of the gold that make’s the directive more powerful and more beautiful. The loop variable will be available inside of our foreach loop. This variable provides access to some useful bits of information of the current loop.

Useful properties the $loop provides :

$loop->indexReturns Index of the current loop iteration which starts at 0
$loop->iterationReturns current loop iteration that starts at 1
$loop->remainingReturns the count of iterations remaining in the loop, like if we have total number of 5 iterations and the current iteration is 2 then, this will return 3.
$loop->countReturns the total number of items in the array being iterated.
$loop->firstReturns true if its the first iteration else returns false.
$loop->lastReturns true if it is the last iteration else returns false.
$loop->evenReturns true if it is the even iteration through the loop.
$loop->oddReturns true if it is the odd iteration through the loop.
$loop->depthReturns the nesting level of the current loop.
$loop->parentIf we have nested foreach loops, using this we can access the parent loop variable.

We can see we have tons of very useful information that we can retrieve using the $loop variable inside @foreach directive. Now, Let’s take a look at one of the examples.

As we can understand the code pretty clear. Just think one time, what we have to go through if we were using PHP foreach loop at this scenario. Hope you enjoyed and learned one or two things from this tutorial . Keep learning keep sharing 🙂

Some of the more useful tips and tutorials for directives are listed below :

  1. Creating your own custom directive
  2. Useful other directives
  3. Search

Happy Coding ! 🙂

Sharing is caring!

Related Post