Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 713
marcelo2605 Avatar asked Jun 26 '26 01:06

marcelo2605


1 Answers

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!

like image 171
Rwd Avatar answered Jun 27 '26 15:06

Rwd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!