Published on

Don't Forget the Laravel Loop Variable

Laravel Loop - Moe Dayraki

The Laravel $loop variable is a powerful variable found inside @foreach. I've been using it a lot lately as I've been working on a lot of data iterations, tables and reports. Let's see how it works and how to use it!😊

The @foreach

The @foreach blade directive works just like foreach in PHP. We just need to add @endforeach when we want to close the loop. The syntax is written like:

@foreach ($collection as $object)
    <p>This is object {{ $object->id }}</p>
@endforeach

or

@foreach ($collection as $key => $object)
    <p>This is object {{ $object->id }}</p>
    <p>Its key is {{ $key }}</p>
@endforeach

Check out the Laravel Documentation for loops for more information.

The $loop

Laravel has made it easier for developers to track their information inside the loop by providing the $loop variable. Useful properties to use:

Property Definition
$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 remain 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.

The $loop->parent property has access to all the properties for the loop but for the parent.

Try using the $loop variable and let me know how you used it! For more details about Laravel, visit Laravel's Documentation

Open Source

The whole project is an open-source project under the MIT License. If you find my content useful, please follow me on Github or Twitter

Last Updated: