Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AbehoM's avatar

Laravel Blade not empty directive

I was reading the docs and I noticed that Laravel only has the @empty directive and it doesn't with the @else so I was wondering, how can I do the inverse and check if the collection is not empty, show the results and if it's empty show a message?

Right now I'm doing something like @if(! $plans->isEmpty()) but it's really ugly compared with the directives solution such as @empty.

0 likes
7 replies
tykus's avatar
@forelse ($things as $thing)

  {{ $thing }}

@empty

    There are no things

@endforelse
AbehoM's avatar

@TYKUS - I can't use @forelse because the @foreach is inside a form so it means that I don't want to display the form with the plans unless it has plans to display

<div class="card-body">
    @if(! $plans->isEmpty())
        <form method="POST" action="{{ route('subscribe.payment') }}">
            @csrf

            @foreach($plans as $plan)
                <p>
                    <input type="radio" name="plan" value="{{ $plan['integrationId'] }}" @if($loop->first) checked @endif>
                    {{ $plan['name'] }}
                </p>
            @endforeach

            <div class="form-group mb-0">
                <button type="submit" class="btn btn-primary">Continue</button>
            </div>
        </form>
    @else
        <div class="alert alert-warning mb-0">
            There are no plans available.
        </div>
    @endif
</div>
Cronix's avatar

I think what you have is the best for your scenario.

AbehoM's avatar

@CRONIX - I feel like I'm doing this way too much and I don't find it that attractive tho, I was thinking about creating a directive for notEmpty with else support but I don't know yet how to do that tho.

Cronix's avatar
Cronix
Best Answer
Level 67

Might not be attractive, but I don't see a good/better way around it for your criteria. If it was just a matter of looping over data if it existed and outputting a message if it didn't, that's simple. You have an extra requirement, which is to output a message (a form in this case) AND loop over the data if there is data to loop over, and output a message if there isn't. That's exactly what your succinct code does. I don't know how you'd improve it really, except make an @empty/@notEmpty directive, which would just replace

@if(! $plans->isEmpty())

with

@notEmpty($plans)

so not really saving much....

3 likes
deepakjd's avatar

Could you have it like this,

@empty($plans)

	There are no plans available.

@endempty

@if (!empty($plans))

	Your form submission
@endif

I thought it looked like what you were looking for.

1 like

Please or to participate in this conversation.