In the Blade templating engine, how to use "if" to determine null or empty?
{{{ Auth::user()->age }}}
In the Blade templating engine, how to use "if" to determine null or empty?
{{{ Auth::user()->age }}}
You can do it as bellow
@if (empty(Auth::user()->age))
// your if code
@else
// your else code
@endif
you can also use:
{{ Auth::user()->age or 'Age not provided' }}
so you will have more clean blade template
This works for me:
{ Auth::user()->age ?: 'Age not provided' }}
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
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 }}
.
© 2022 - 2024 — McMap. All rights reserved.