i-faith
i-faith

Reputation: 499

Check if null and empty string in Laravel view

in my view I have to output separately the one that is null and the one that is empty string

so i have this:

@if( $str->a == null)
... // do somethin
@endif

@if( $str->a == '')
... // do somethin
@endif

the problem is they the same result.

Thanks

Upvotes: 26

Views: 193964

Answers (5)

Hashim Aziz
Hashim Aziz

Reputation: 6052

There's also PHP's isset() function, which Laravel uses under the hood in its @isset Blade helper, making it a natural option if you're not in a Blade template but want to do something similar.

Upvotes: 0

Hiren Pipariya
Hiren Pipariya

Reputation: 80

You can try this

@isset($str->a)
    // $str->a is defined and is not null...
@endisset

@empty($str->a)
    // $str->a is "empty"...
@endempty

If Statements Laravel docs

Upvotes: 4

jvk
jvk

Reputation: 2201

@if( !empty($str->a))
... // do somethin
@endif

This are consider for empty

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

Upvotes: 28

Jim Wright
Jim Wright

Reputation: 6058

$str->a can't be null and '' at the same time. Have you tried @elseif?

@if( is_null($str->a))
... // do somethin
@elseif( $str->a == '')
... // do somethin
@endif

actually, it should only shows the ones that is null and not the one that is empty.

It sounds like you want to check if $str->a is a valid string or not. As suggested in comments by @GrumpyCrouton you can use empty().

@if( empty($str->a))
... // do somethin
@endif

Upvotes: 2

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

In the comments you've said you only want to check if it is null. So, use is_null():

@if (is_null($str->a))
    // do somethin
@endif

Upvotes: 31

Related Questions