Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

moshemo's avatar
Level 12

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.

0 likes
3 replies
jlrdw's avatar

Mysql wouldn't store a date as a string unless the field type is wrong, so double check that field data type.

1 like
martinbean's avatar
Level 80

@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.

2 likes

Please or to participate in this conversation.