Carbon get current date if variable is null

家住魔仙堡 提交于 2019-12-12 17:08:48

问题


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?


回答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!




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/45118001/carbon-get-current-date-if-variable-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!