Search code examples
phplaravellaravel-bladephp-carbon

Carbon get current date if variable is null


Inside my blade edit form, I have this:

<input type="text" name="birth" class="form-control" id="birth" value="{{ \Carbon\Carbon::parse($associado->birth)->format('d/m/Y') }}">

The problem is: if $associado->birth is NULL in database, Carbon is returning current date.

What can I do to avoid that?


Solution

  • You would need to check if the value is null.

    Furthermore, you could add birth to the $dates array property in your eloquent model.

    protected $dates = [
        'dates'
    ];
    

    This will tell the eloquent model to cast this column to a Carbon instance like it does for created_at and updated_at. If the column if null it will simply return null.

    Your code would then look something like:

    {{ $associado->birth ? $associado->birth->format('d/m/Y')  : null }}
    

    Hope this helps!