我知道如何使用Date和DateTime.但在这种情况下,我希望我的数据是2023-03-03星期五.Laravel 提供这样的东西吗?
这是我的代码
$table->date('estimate_time_arrival');
我怎么修改它呢?
我知道如何使用Date和DateTime.但在这种情况下,我希望我的数据是2023-03-03星期五.Laravel 提供这样的东西吗?
这是我的代码
$table->date('estimate_time_arrival');
我怎么修改它呢?
我的建议是以默认格式(Y-m-d)存储日期.使用拉威尔投射功能.
protected function estimateTimeArrival(): Attribute
{
return Attribute::make(
get: fn (string $value) => Carbon::parse($value)->format('Y-m-d l'),
);
}
如果打印$record->estimate_time_arrival
和$record->toArray()
,则输出如下
方法2:在你的模型中有Attribute Casting个
protected $casts=[
'estimate_time_arrival' => 'datetime:Y-m-d l',
];
如果打印$record->estimate_time_arrival
和$record->toArray()
,则输出如下
如果您看到输出,那么如果我们try 直接访问,那么它将返回Carbon Object,而格式化输出仅在您使用toArray()
时返回
方法三:
protected $casts=[
'estimate_time_arrival' => 'datetime:Y-m-d l',
];
如果打印$record->estimate_time_arrival->format('Y-m-d l')
和$record->toArray()
,则输出如下