Laravel Blade how to use if statement for null or empty
Asked Answered
D

5

6

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

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

Dualism answered 14/5, 2015 at 18:23 Comment(2)
laravel.com/docs/5.0/templates#other-blade-control-structuresRevisionism
no this is for $foo and my problem for Auth::user()->***Dualism
T
33

You can do it as bellow

    @if (empty(Auth::user()->age))
      // your if code
    @else
     //  your else code
    @endif
Trichology answered 14/5, 2015 at 18:28 Comment(0)
K
3

you can also use:

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

so you will have more clean blade template

Kindly answered 4/4, 2019 at 14:2 Comment(1)
I don't no why It's not working for me, it always returns '1' as result, just like the result of a boolean expression.Mancini
A
2

This works for me:

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

Anear answered 29/6, 2019 at 20:3 Comment(0)
M
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

Mahon answered 1/1, 2021 at 0:35 Comment(0)
M
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 }}.

Melia answered 28/4, 2020 at 21:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.