laravel 如果变量为空,Carbon 获取当前日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45118001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Carbon get current date if variable is null
提问by marcelo2605
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.
问题是:如果$associado->birth
数据库中为 NULL,Carbon 将返回当前日期。
What can I do to avoid that?
我该怎么做才能避免这种情况?
回答by Rwd
You would need to check if the value is null
.
您需要检查该值是否为null
。
Furthermore, you could add birth
to the $dates
array property in your eloquent model.
此外,您可以在 eloquent 模型中添加birth
到$dates
数组属性。
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.
这将告诉 eloquent 模型将此列转换为一个Carbon
实例,就像它为created_at
and所做的那样updated_at
。如果列如果null
它将简单地返回空值。
Your code would then look something like:
您的代码将如下所示:
{{ $associado->birth ? $associado->birth->format('d/m/Y') : null }}
Hope this helps!
希望这可以帮助!
回答by Daniel
Check if $associado->birth
is NULL before parsing it with Carbon.
$associado->birth
在用 Carbon 解析之前检查是否为 NULL。
If it has a true value, it is not NULL and you can parse it - otherwise just return set null in your value.
如果它有一个真值,它不是 NULL,你可以解析它 - 否则只需在你的值中返回 set null 。
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.
再说一次,当使用这么多逻辑时,它应该放在它自己的函数中。
回答by Sagar Gautam
You can do it with createFromFormat()
of Carbon
.
你可以用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.
这将检查存储在数据库中的日期字符串值,并在Null
值的情况下为空。
Hope you understand.
希望你能理解。