1

In Smarty Templates I can simply check a value in my case an array and if empty I can output a default value like this:

{$smarty.session.foo['bar']|default:"empty"}

How can I simply do the same in laravel blade without nested @if statements?

@if(session()->has('foo'))
    @if( ! empty( session('foo')->bar ) )
        {{ session('foo')->bar }}
    @else
       empty
    @endif
@endif

How can I do this shorthand?

Frank
  • 25
  • 1
  • 6
  • figure out the value you want BEFORE sending to the view – delboy1978uk Jul 17 '18 at 14:16
  • Possible duplicate of [How to echo a default value if value not set blade](https://stackoverflow.com/questions/18023480/how-to-echo-a-default-value-if-value-not-set-blade) – Nima Jul 17 '18 at 14:20
  • I'm totally not a fan of logic in views. Everything should be figured out prior to being sent to the view. The ideal view only has loops and echoes. – delboy1978uk Jul 17 '18 at 14:21
  • @delboy1978uk for business logic I'd agree, but checking if something is empty seems perfectly fine for a view. – Devon Bessemer Jul 17 '18 at 14:22

1 Answers1

1

Blade has a built in structure for this using OR.

{{ session('foo')->bar OR 'empty' }}

Blade also accepts regular PHP, so you can use the elvis operator to skip any false value:

{{ session('foo')->bar ?: 'empty' }}

Or the null-coalescing operator to skip null values (PHP7+).

{{ session('foo')->bar ?? 'empty' }}

For all of these though, session('foo') would still need to return an object.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • And what if is not an Object? I think that's my main Issue. Some Sessions are only set in special cases and they can by empty. – Frank Jul 18 '18 at 14:55
  • Null-coalescing should work with a non-object, but the other two examples won't I believe. They would issue a notice of accessing a property on a non-object. – Devon Bessemer Jul 18 '18 at 14:58