Laravel:如何设置模型属性转换的日期格式? [英] Laravel: how to set date format on model attribute casting?

查看:1934
本文介绍了Laravel:如何设置模型属性转换的日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有模特:

protected $casts = [
    'date' => 'date',
];

laravel是否具有设置转换格式的功能,例如:

Does laravel have some ability to set cast format, something like:

protected $casts = [
    'date' => 'date_format:d/m/yyyy',
];

?

已编辑

我尝试过:

在模型中:

protected $dateFormat = 'm/d/Y';

protected $dates = ['driver_expiration', 'created_at', 'updated_at', 'deleted_at'];

protected $casts = [
    'driver_expiration'     => 'date',
];

我将日期(driver_expiration)保存为'01/012016',但日期保存了注册信息.

I saved date(driver_expiration) as '01/012016' but date is saved 0000-00-00.

laravel文档: https://laravel.com/docs/5.1/eloquent-mutators 告诉我们$ dateFormat仅适用于时间戳("created_at","updated_at","deleted_at")

laravel documentation: https://laravel.com/docs/5.1/eloquent-mutators Tell us $dateFormat works only for timestamps ('created_at', 'updated_at', 'deleted_at')

推荐答案

除了强制转换日期格式,您还可以使用mutator设置所需的格式:

Instead of casting a date format, you can use mutators to set the format you like:

例如,如果您的列名为date,则可以在模型中添加以下函数:

For example, if your column was called date, you can add the following function to your model:

public function setDateAttribute( $value ) {
  $this->attributes['date'] = (new Carbon($value))->format('d/m/y');
}

使用CamelCase,setDateAttribute始终为set[ColumnName]Attribute格式. $this->attributes['date']部分中的date也必须与表中的实际列名匹配.

The setDateAttribute is always in the format set[ColumnName]Attribute, using CamelCase. The date in the $this->attributes['date'] part must also match your actual column name in the table.

当您在数据库中记录createupdate时,上述功能将自动更改格式.

When you create or update a record in your database, the format will automatically be changed by the function above.

注意:您可能需要在模型顶部添加use Carbon\Carbon语句才能使用Carbon库.

Note: You may need to add the use Carbon\Carbon statement to the top of your Model to use the Carbon library.

在此处查看其他示例.

更新

(可选)您可以使用以下方法为date列定义格式:

Optionally, you can define a format for date columns using:

protected $dateFormat = 'Y-m-d';

这篇关于Laravel:如何设置模型属性转换的日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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