You need to tell laravel to cast it https://laravel.com/docs/9.x/eloquent-mutators#date-casting
Carbon Date Being Saved as String in Database
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.
@moshemo Well yes, it gets saved as a string because database don’t know what “Carbon” is. Carbon is a PHP library. You can’t store PHP objects in a database.
Instead, you want to cast the column as a date column so that when the value is retrieved, it’s cast back to a Carbon instance so you can call Carbon methods on it.
Please or to participate in this conversation.