2

I have this code in blade template :

{{ $birthday->format('m/d/Y') }}

I am getting this error when $birthday is null, how to suppress this exception?

I want to show empty string when $birthday is null, I tried this two solutions but with no success:

{{ $birthday->format('m/d/Y') or '' }}

And:

{{ @$birthday->format('m/d/Y') }}

Any suggestions ? I would like blade solution not in eloquent model...

fico7489
  • 7,931
  • 7
  • 55
  • 89
  • 1
    The cause of this is an old design problem in the engine of PHP. All errors can be converted to exceptions or can be silenced with `@` except when a method is called on a non-object. That case is somehow special. I don't think they will ever fix this. – Crouching Kitten Jan 31 '17 at 13:35
  • @Jonathan ahahah who said that I don't know how to check variable's existence ? Why did you assume ? I am just looking for ideas for elegant solution....In other php template engines exists feature that I am looking for.... – fico7489 Jan 31 '17 at 13:56
  • @Jonathan How do you think I solved this issue until now, I used if statement, but my question is if there is any blade feature/solution like in other php templating engines, in smarty templating engine you can use this code : {{ @$birthday->format('m/d/Y') }} . So legit answer to my question is "No, blade can't do this"!!!!!!!! – fico7489 Feb 01 '17 at 06:11
  • I'd like to see how the "smarty" code is different. The rendered output is almost exactly as you see it in blade in your last example. `format('m/d/Y')); ?>`. Garbage in, garbage out – Jonathan Feb 01 '17 at 09:38

9 Answers9

3

Use ternary operator:

{{ is_null($birthday) ? '' : $birthday->format('m/d/Y') }}
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
2

You could use a null coalesce to set a default value for your variables.

{{ $var ?? 'default' }}

or if you have PHP <7

<?php isset($var) ? $var  : 'default'; ?>

{{ $var }}
online Thomas
  • 8,864
  • 6
  • 44
  • 85
  • this : {{ $var ?? 'default' }} is cool, but will not work with {{ $var->someFunction() ?? 'default' }} – fico7489 Jan 31 '17 at 14:00
  • Why would it not work? And I really think function calls should be in the controller and not in the view when possible! – online Thomas Jan 31 '17 at 14:14
2

Dates from an Eloquent model returns either a Carbon/Carbon object or null if not set. If you want the date to be an empty string if it doesn't exists you can create an accessor.

class Foo extends Eloquent {
    public function getBirthdayAttribute() {
        return isset($this->attributes['birthday']) && $this->attributes['birthday'] instanceof \DateTime ? $this->attributes['birthday']->format('m/d/Y') : '';
    }
}
Marwelln
  • 28,492
  • 21
  • 93
  • 117
2

All other answers are way too complex or won't work in case you need to call a function on the variable in question. Fortunately Laravel has a nice trick for this; you can use optional helper:

{{ optional($birthday)->format('m/d/Y') }}

It's available since Laravel 6 https://laravel.com/docs/8.x/helpers#method-optional

Arno van Oordt
  • 2,912
  • 5
  • 33
  • 63
1

try this one:

{{isset($birthday)? $birthday->format('m/d/Y') : '' }}

1

You may construct blade if statements using the @if, @elseif, @else, and @endif directives. These directives function identically to their PHP counterparts:

  @if($birthday)
    {{ $birthday->format('m/d/Y') }}
   @endif

note: using a @if in a @foreach $x will repeat the if statement for each $x More about Laravel Blade

EDIT

This is the elegant solution u are looking for

{{ $birthday->format('m/d/Y')  ?: '' }}
Jesse de gans
  • 1,432
  • 1
  • 14
  • 27
  • Then I would need to repeat this code 200 and more times: @if($variable) {{ $variable }} @endif It is not elegant and not DRY valid... – fico7489 Jan 31 '17 at 13:06
  • Please edit your question with the full code :) so i can observe what u need all i know now is that u need to show $birthday when its value is set. Are u using a blade foreach or a for loop? – Jesse de gans Jan 31 '17 at 13:08
  • I think question is explained enough. I am looking for soulution how to echo empty string when variable is null...But I am looking for elegant solution.... – fico7489 Jan 31 '17 at 13:58
1

As of PHP 8.0 you can use nullsafe operator (?->) and when $birthday is null it translates whole expression to null.

{{ $birthday?->format('m/d/Y') }}
Jsowa
  • 9,104
  • 5
  • 56
  • 60
0

My solution is to extend blade :

class AppServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('datetime', function ($expression) {
            if($expression == null){
                return '';
            }else{
                return "<?php echo ($expression)->format('m/d/Y'); ?>";
            }
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
fico7489
  • 7,931
  • 7
  • 55
  • 89
0

i often use

{{ $var->prop ? $var->prop->format('d/m/Y') : '' }}
Ezequiel García
  • 2,616
  • 19
  • 12