Carbon get current date if variable is null

10,650

Solution 1

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!

Solution 2

You can do it with createFromFormat() of Carbon.

value = "{{$associado->birth ? \Carbon\Carbon::createFromFormat('d\m\Y',
          $associado->birth)->toDateString() : null}}"

This will check string value of date stored in database and give empty in case of Null value.

Hope you understand.

Solution 3

Check if $associado->birth is NULL before parsing it with Carbon.

If it has a true value, it is not NULL and you can parse it - otherwise just return set null in your value.

Here is an example using the ternary operator

value="{{ $associado->birth ? \Carbon\Carbon::parse($associado->birth)->format('d/m/Y') : null}}

Then again, when using this much logic, it should be put inside it's own function.

Share:
10,650
marcelo2605
Author by

marcelo2605

Updated on June 07, 2022

Comments

  • marcelo2605
    marcelo2605 almost 2 years

    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?

    • Rwd
      Rwd almost 7 years
      Is $associado an Eloquent model?