如果变量为null,则Carbon获得当前日期 [英] Carbon get current date if variable is null

查看:152
本文介绍了如果变量为null,则Carbon获得当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在刀片编辑表单中,我有以下内容:

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') }}">

问题是:如果数据库中$associado->birth为NULL,则Carbon返回当前日期.

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

如何避免这种情况?

推荐答案

您需要检查值是否为null.

此外,您可以在雄辩的模型中将birth添加到$dates数组属性中.

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

protected $dates = [
    'dates'
];

这将告诉雄辩的模型将其列强制转换为Carbon实例,就像created_atupdated_at一样.如果该列为null,它将简单地返回null.

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.

您的代码将如下所示:

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

希望这会有所帮助!

这篇关于如果变量为null,则Carbon获得当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆