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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:18:05  来源:igfitidea点击:

Carbon get current date if variable is null

phplaravellaravel-bladephp-carbon

提问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->birthis 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 birthto the $datesarray property in your eloquent model.

此外,您可以在 eloquent 模型中添加birth$dates数组属性。

protected $dates = [
    'dates'
];

This will tell the eloquent model to cast this column to a Carboninstance like it does for created_atand updated_at. If the column if nullit will simply return null.

这将告诉 eloquent 模型将此列转换为一个Carbon实例,就像它为created_atand所做的那样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->birthis 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 Nullvalue.

这将检查存储在数据库中的日期字符串值,并在Null值的情况下为空。

Hope you understand.

希望你能理解。