Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Identifying even and odd iterations in Laravel Blade

When designing UI elements such as zebra strips in the tables, you’d need to identify if the loop iteration is even or odd and based on that you’d set the backgroud color of the row.

In Blade templates of Laravel, one way to achieve this would be to use something like following,

@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->iteration % 2 == 0)
            This is an even iteration
        @else 
            This is an odd iteration
        @endif
    @endforeach
@endforeach

The syntax, as you can see, is pretty dense looking. But, Laravel has something tidy and better way to do it.

Using even and odd flags

There exists two convenience properties in the Blade’s $loop varible through which you can directly check the even and odd iterations like so.

@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->even)
            This is an even iteration
        @elseif ($loop->odd)
            This is an odd iteration
        @endif
    @endforeach
@endforeach

Here, even will check whether current iteration is an even iteration through the loop. And odd will check whether current iteration is an odd iteration through the loop.

You can learn more about such convenience properties of $loop in the official documents here.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?