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

查看:73
本文介绍了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",但日期保存为 0000-00-00.

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

推荐答案

你可以使用 mutators 来设置你喜欢的格式,而不是强制转换日期格式:

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

setDateAttribute 总是采用 set[ColumnName]Attribute 格式,使用 CamelCase.$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 CarbonCarbon 语句以使用 Carbon 库.

Note: You may need to add the use CarbonCarbon 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天全站免登陆