DEV Community

Cover image for Fixed: Laravel Blade @else Inside @foreach Syntax Error (Laravel 12 + PHP 8.5)
Dev Stack
Dev Stack

Posted on • Originally published at devstackdaily.blogspot.com

Fixed: Laravel Blade @else Inside @foreach Syntax Error (Laravel 12 + PHP 8.5)

Ran into this while working on a Laravel 12 + PHP 8.5 project — sharing in case it saves someone the debugging time.

The problem

Wrote an @else inside an @foreach loop in Blade, expecting it to show a fallback when the collection is empty. Instead, got:

ParseError
syntax error, unexpected token "else", expecting end of file

Why it happens

Blade's @foreach compiles straight into a native PHP foreach loop — and PHP's foreach has no else branch, period. Blade doesn't add one; it just passes through what you wrote as literal PHP, so the compiled output is invalid PHP.

The fix

Laravel already has a directive built for exactly this: @forelse.

@forelse ($items as $item)
    <p>{{ $item->name }}</p>
@empty
    <p>No items found.</p>
@endforelse
Enter fullscreen mode Exit fullscreen mode

@foreach@forelse, @else@empty, @endforeach@endforelse. That's the whole fix.

I wrote up the full breakdown (with the compiled PHP output showing exactly why it breaks) here: https://devstackdaily.blogspot.com/2026/07/fixed-laravel-blade-else-inside-foreach.html

Curious if others have hit this — did @forelse click for you right away or did it take a minute to find?

Top comments (0)