Check if $slot is empty in laravel blade component
Asked Answered
P

3

9

I have a component that outputs the $slot. But I want to do something like:

Component

<x-alert></x-alert>
<div>
@if ($slot)
    {{ $slot }}
@else
    No available content
@endif
</div>
Poland answered 5/9, 2021 at 6:54 Comment(4)
what is the problem with this code exactly ?Crackbrained
It always runs the if condition rather than the else one, even when I don't add any items to it.Poland
what is the type of the variable $slot ? is it an array ?Crackbrained
Not suer, it's basically any content that I type between the opening and closing tags of the component.Poland
A
25

$slot is an instance of the Illuminate\Support\HtmlString class. So you can use the isNotEmpty method:

<div>
@if ($slot->isNotEmpty())
    {{ $slot }}
@else
    No available content
@endif
</div>
Audrieaudris answered 5/9, 2021 at 18:7 Comment(0)
C
3

the variable $slot in laravel components is prepared as Object of type Illuminate\Support\HtmlString
so it need to be checked like this :

<div>
@if(strlen($slot->toHtml()) != 0)
    {{$slot}}
@else
    slot is empty
@endif
Crackbrained answered 5/9, 2021 at 8:0 Comment(0)
R
3

Try this :

<div>
@if (isset($slot) && $slot != null )
    {{ $slot }}
@else
    No available content
@endif
</div>
Reason answered 8/9, 2021 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.