[英]Laravel blade does not respect date cast formatting
I have a birth date field in users table我在用户表中有一个出生日期字段
$table->date('dob');
User model has Casts用户模型有演员表
protected $casts = [
'dob' => 'date:d-m-Y'
];
In Blade,在刀锋中,
{{$user->dob}}
I was expecting 26-11-2019 but found it shows 2019-11-26 00:00:00我期待 26-11-2019 但发现它显示 2019-11-26 00:00:00
Why I need to format the date again in blade when display?为什么显示时需要在刀片中再次格式化日期?
What did I miss?我错过了什么? Or what I was expecting, is not the purpose of formatting?或者我所期待的,不是格式化的目的吗?
protected $casts = [...]
tells Laravel to treat the properties as Carbon
instances, but you still need to format them: protected $casts = [...]
告诉 Laravel 将属性视为Carbon
实例,但您仍然需要格式化它们:
{{ $user->dob->format('d-m-Y') }}
As far as I'm aware, there isn't a way to output a default format, unless you use an accessor
:据我所知,除非您使用accessor
,否则无法输出默认格式:
In your User.php
model:在您的User.php
模型中:
public function getDobFormattedAttribute(){
return $this->dob->format('y-m-D');
}
Then in your view:那么在你看来:
{{ $user->dob_formatted }}
Date casting uses only for arrays or JSON, as explained here:日期转换仅用于数组或 JSON,如下所述:
https://laravel.com/docs/6.x/eloquent-mutators#date-casting https://laravel.com/docs/6.x/eloquent-mutators#date-casting
You can try to do it via mutator:您可以尝试通过 mutator 来做到这一点:
https://laravel.com/docs/6.x/eloquent-mutators#date-mutatorshttps://laravel.com/docs/6.x/eloquent-mutators#date-mutators
protected $dates = [
'dob', // it will be 'Y-m-d H:i:s'
];
protected $dateFormat = 'd-m-Y'; // but you can redefine it
that will only work when you use a ->toArray()
or ->toJson()
on the object or collection in question, from the doc here https://laravel.com/docs/6.x/eloquent-mutators#date-casting仅当您在相关对象或集合上使用->toArray()
或->toJson()
,来自此处的文档https://laravel.com/docs/6.x/eloquent-mutators#date -铸件
A way around that of you weren't using any of the above function call is to create an accessor or getter method in the model.您没有使用任何上述函数调用的方法是在模型中创建访问器或 getter 方法。
use Carbon\Carbon; // import the Carbon lib.
protected $dates = ['dob'];
public function getDobAttribute($value)
{
return Carbon::createFromFormat('d-m-Y', $value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.