6

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

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

paradox
  • 113
  • 1
  • 1
  • 7

5 Answers5

33

You can do it as bellow

    @if (empty(Auth::user()->age))
      // your if code
    @else
     //  your else code
    @endif
Vishal Wadhawan
  • 1,085
  • 1
  • 9
  • 11
3

you can also use:

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

so you will have more clean blade template

Jorge Arimany
  • 5,814
  • 2
  • 28
  • 23
2

This works for me:

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

Razi Kallayi
  • 862
  • 9
  • 19
2

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

the_sky_is_pink
  • 109
  • 2
  • 11
0

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 }}.

arthurborges
  • 15
  • 2
  • 5