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.
CodePudding user response:
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:
class Transaction extends Model {
protected $casts = [
'date' => 'date'
];
...
}
Now, when you retrieve a Transaction
model record, the date
attribute will automatically be a Carbon
instance:
$transaction = Transaction::first();
dd($transaction->date, get_class($transaction->date));
// ^ Carbon\Carbon @1646769789^ {#4514 ... }, `Carbon\Carbon`
Now, you can perform Carbon logic, simply by chaining:
{{ $transaction->date->format('Y-m-d') }}
// `2022-03-08`
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