如果变量为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?

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!

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.

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.