paradox
paradox

Reputation: 113

Laravel Blade how to use if statement for null or empty

In the Blade templating engine, how to use "if" to determine null or empty?

{{{ Auth::user()->age }}}

Upvotes: 6

Views: 45951

Answers (5)

the_sky_is_pink
the_sky_is_pink

Reputation: 139

Summarizing Jorge and Razi's answers, cleanest way to do it is this:

{{ Auth::user()->age ?? 'Age not provided' }}

also this:

{{ Auth::user()->age ?: 'Age not provided' }}

but this one doesn't work (I'm on Laravel 8, this only works with lower Laravel versions):

{{ Auth::user()->age or 'Age not provided' }}

If you try this last method, it returns 1 instead of what you want.

Also check this question: Check if variable exist in laravel's blade directive

Upvotes: 2

arthurborges
arthurborges

Reputation: 15

In my case, as I was using HeidiSQL as a DB Manager, I had to guarantee that the column field was really NULL. To do that, I clicked on the field with the right mouse button, clicked on "Insert value", then on "NULL". (It's the same as Shift+Ctrl+N). In the beginning, I was just entering NULL on the field, which is a String I guess, so it was always "truthy", not NULL. Doing that solved the problem for me, even writing {{ Auth::user()->age }}.

Upvotes: 0

Razi Kallayi
Razi Kallayi

Reputation: 890

This works for me:

{ Auth::user()->age ?: 'Age not provided' }}

Upvotes: 2

Jorge Arimany
Jorge Arimany

Reputation: 5882

you can also use:

{{ Auth::user()->age or 'Age not provided' }}

so you will have more clean blade template

Upvotes: 3

Vishal Wadhawan
Vishal Wadhawan

Reputation: 1085

You can do it as bellow

    @if (empty(Auth::user()->age))
      // your if code
    @else
     //  your else code
    @endif

Upvotes: 33

Related Questions