Small but Mighty Blade Features in Modern Laravel

· 3 min read

Laravel continuously rolls out Blade updates with every new generation. Not only do they solve UI components, but small granular directives also make our code much cleaner.

1. Class Importing with @use (Laravel 11)

Perfect for those times when you need to call an Enum or a constant and don’t want to type out a lengthy Namespace.

@use('App\Enums\PostStatus')

@if ($post->status === PostStatus::PUBLISHED)
    <span class="text-green-500">Published</span>
@endif

Or set an alias:

@use('App\Models\User', 'UserModel')

2. Managing Element States with @checked, @selected, @disabled

Previously, we had to write tedious ternary operators:

<input type="checkbox" name="active" value="1" {{ $user->active ? 'checked' : '' }}>

With Modern Blade:

<input type="checkbox" name="active" value="1" @checked(old('active', $user->active))>

<select name="role">
    <option value="admin" @selected($user->role == 'admin')>Admin</option>
    <option value="user" @selected($user->role == 'user')>User</option>
</select>

<button type="submit" @disabled($errors->isNotEmpty())>
    Submit
</button>

3. Rendering a Fragment of a View with @fragment (Hot for HTMX / Livewire)

Many developers use AJAX-optimizing libraries like HTMX or Turbo. Laravel natively supports returning just a specific "piece" of a view via @fragment.

The view file posts/index.blade.php:

<div>
    <h1>Posts List</h1>

    @fragment('post-list')
        <ul>
            @foreach($posts as $post)
                <li>{{ $post->title }}</li>
            @endforeach
        </ul>
    @endfragment
</div>

In the Controller, if there's an AJAX/HTMX request requiring just this list:

return view('posts.index', ['posts' => $posts])->fragment('post-list');

The returned result contains ONLY the chunk inside @fragment('post-list'), saving copious amounts of bandwidth.

4. Loop Condition Variables ($loop)

Inside any @foreach block, the magical $loop variable is always available:

@foreach ($users as $user)
    @if ($loop->first)
        Manager: {{ $user->name }}
    @else
        Employee: {{ $user->name }}
    @endif
    
    <span class="class-{{ $loop->even ? 'gray' : 'white' }}">
        Iteration index: {{ $loop->iteration }}
    </span>
@endforeach

Common properties include: $loop->index (starts at 0), $loop->iteration (starts at 1), $loop->remaining, $loop->last.

These are various Blade "tricks and tips" that accelerate coding speed and prevent source code from turning into an unreadable matrix.

Comments