碳日期在数据库中保存为字符串
我正在尝试使用工厂播种一些数据。我试图播种的字段之一是日期字段——我在工厂中使用以下代码来实现这一点:
return [
...
'date' => Carbon::now()->subDays(rand(1, 365))->startOfDay()
];
问题是,它作为字符串保存在数据库中——这意味着我不能这样做我的刀片模板中包含以下内容:{{ $transaction->date->format('M, d Y') }}
,
当我尝试这样做时,我收到以下错误消息:< code>调用成员函数format() on字符串。
作为一个测试,我在我的刀片模板中尝试了相同的代码,只需将 created_at
替换为 date
- 它就能按照我想要的方式工作。即,这有效:{{ $transaction->created_at->format('M, d Y') }}
。
如果重要的话,在我的迁移文件中使用 $table->timestamps()
创建 created_at
字段,而创建 date
字段如下:$table->date('date');
。
知道我需要做什么才能让它发挥作用吗?
谢谢。
I am trying to seed some data using Factories. One of the fields I'm trying to seed is a date field -- and I do so with the following code in my factory:
return [
...
'date' => Carbon::now()->subDays(rand(1, 365))->startOfDay()
];
The problem is, this is getting saved in the database as a string -- which means that I CANNOT do the following in my blade templates: {{ $transaction->date->format('M, d Y') }}
,
When I try that, I get the following error message: Call to a member function format() on string
.
Just as a test, I tried in my blade template the same exact code, just switching out created_at
for date
- and it works as I want. I.e., this works: {{ $transaction->created_at->format('M, d Y') }}
.
In case it matters, the created_at
field is created using $table->timestamps()
in my migration file whereas the date
field is created as follows: $table->date('date');
.
Any idea what I need to do in order to get this to work?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Laravel 提供了一种将某些 Model 属性“转换”为特定数据类型的方法,包括字符串、整数、日期等。由于 Carbon 内置于 Laravel 中,指定
date
类型会自动将 Model 属性转换为碳实例。您需要做的就是向模型提供该逻辑:现在,当您检索
Transaction
模型记录时,date
属性将自动成为Carbon
code>实例:现在,您可以简单地通过链接来执行Carbon逻辑:
有更多的转换类型可用,并且您可以通过简单地将它们作为键/值对添加到
$casts
数组来指定多个属性转换。完整文档位于:https://laravel.com/docs/9 .x/eloquent-mutators#attribute-casting
Laravel provides a method to "cast" certain Model attributes to specific datatypes, including strings, integers, dates, etc. Since Carbon is built in to Laravel, specifying the
date
type auto-converts Model attributes to a Carbon instance. All you need to do is provide that logic to your model:Now, when you retrieve a
Transaction
model record, thedate
attribute will automatically be aCarbon
instance:Now, you can perform Carbon logic, simply by chaining:
More casting types are available, and you can specify multiple attribute casts by simply adding them as key/value pairs to the
$casts
array. Full documentation is here:https://laravel.com/docs/9.x/eloquent-mutators#attribute-casting