Sling Academy
Home/PHP/Laravel: Styling odd/even rows in a Blade loop (5 approaches)

Laravel: Styling odd/even rows in a Blade loop (5 approaches)

Last updated: January 15, 2024

Introduction

Laravel’s Blade templating engine provides an expressive and elegant way to iterate through data and apply different styles to odd and even rows. Such styling can be instrumental in improving the readability of tabulated data by distinguishing between adjacent rows. This guide will walk you through several methods – starting from the most straightforward approach to more complex solutions – showing how to style odd and even rows using Blade loops in Laravel.

Understanding Blade Syntax

Before diving into the styling aspect, it’s important to understand the basics of Blade syntax. Blade templates are mostly constructed with HTML, and Blade-specific directives are denoted by @. For instance, a simple foreach loop can be written as:

@foreach ($items as $item)
    <div>{{ $item }}</div>
@endforeach

With this foundation, we can begin applying our styles.

Method 1: Using the loop variable

The simplest way to style odd/even rows in Blade is by utilizing the built-in $loop variable. It provides a variety of properties, with iteration being ideal for our purpose. Here’s an example:

@foreach ($items as $item)
    <div class="{{ $loop->iteration % 2 == 0 ? 'even' : 'odd' }}">
        {{ $item }}
    </div>
@endforeach

In this snippet, the div class dynamically changes based on the iteration index. For even rows, the class ‘even’ is applied, and ‘odd’ for the others. The % operator calculates the remainder of the iteration index divided by 2, determining the row type.

Method 2: Using CSS nth-child

If you prefer to keep your styles strictly in CSS, the :nth-child pseudo-class is an excellent alternative. You can apply it to your table rows or any list of elements without making any changes to your Blade template. Here’s a CSS example:

tr:nth-child(odd) {
    background-color: #f2f2f2;
}

tr:nth-child(even) {
    background-color: #ffffff;
}

And the Blade template remains clean and straightforward:

@foreach ($items as $item)
    <tr>
        <td>{{ $item }}</td>
    </tr>
@endforeach

With the CSS handling the styles, your Blade template is kept free from inline styling logic, making it more readable and maintainable.

Method 3: Custom Blade Directives

For more complex scenarios, you might want to define custom Blade directives. This method allows for greater flexibility. You can create a directive for odd and even styles as follows:

@bladeDirectives('evenodd', function($expression) {
    return "";
});

Now, you can use this directive in your Blade template:

@foreach ($items as $item)
    <div class="@evenodd($loop->iteration)">
        {{ $item }}
    </div>
@endforeach

This allows you to define the styling logic once and reuse it across multiple templates. Note that @bladeDirectives is not an actual Blade method but a placeholder for registering a new directive, typically done within a Service Provider.

Method 4: Combining PHP and Blade

When you need more advanced control and perhaps some business logic in determining styles, you might mix PHP and Blade. Although it may appear less elegant, this approach offers maximum control:

@php
    $styleMapping = [
        'oddStyle' => 'background-color: #f2f2f2;',
        'evenStyle' => 'background-color: #ffffff;'
    ];
@endphp

@foreach ($items as $item)
    @php
        $style = $loop->iteration % 2 == 0 ? $styleMapping['evenStyle'] : $styleMapping['oddStyle'];
    @endphp
    <div style="{{ $style }}">
        {{ $item }}
    </div>
@endforeach

This example demonstrates inlining PHP variable assignment within a Blade loop. One advantage of this method is its ability to extract and dynamically adjust styling definitions based on complex conditions not readily manageable through Blade directives alone.

Method 5: Using Collections

In some cases, the advanced features of Laravel Collections might be necessary. Collections provide a fluent, convenient wrapper for working with arrays of data. Consider an example where we want to associate each item with a specific style:

$items->each(function($item, $key) use ($someCondition) {
    $item->rowStyle = $key % 2 == 0 ? 'evenStyle' : 'oddStyle';
    if ($someCondition) {
        $item->rowStyle .= ' additionalStyle';
    }
});

Then, in the Blade template, simply apply the styles:

@foreach ($items as $item)
    <div class="{{ $item->rowStyle }}">
        {{ $item }}
    </div>
@endforeach

This method takes advantage of the Laravel collections’ ability to manipulate data before it hits the view.

Conclusion

In this guide, you’ve learned several methods to style odd and even rows within a Blade loop in Laravel. Whether you prefer simple solutions using built-in helpers or more complex approaches that separate logic and presentation, Laravel and Blade offer flexible options to achieve your styling objectives cleanly and efficiently.

Next Article: Directives in Laravel Blade: Tutorial & Examples

Previous Article: Laravel: How to break a foreach loop in Blade

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array