Laravel model item set carbon item but returns string
Asked Answered
L

1

5

I have added a datetime in the database schema:

$table->dateTime('send_at')->nullable();

I have set the attribute to a Carbon instance in the seeder:

$invoice->send_at = Carbon::now();

When I try to get the type of the attribute inside the controller it returns a string:

dd(gettype($data['invoices'][0]->send_at));

What is going on? And how can I be sure that it's a Carbon Object instead of a string?

Laveralavergne answered 1/11, 2020 at 14:39 Comment(0)
B
7

On your model, you need to define $dates property to create Carbon instance automatically for the column :

protected $dates = ['send_at'];

On Since Laravel 8:

protected $casts = [
    'send_at' => 'datetime',
];
Bolten answered 1/11, 2020 at 14:41 Comment(3)
You are my hero! Thanks! Just another question: why isn't that necessary for the created_at and updated_at attributes?Laveralavergne
created_at and updated_at also a Carbon instance, set by default on Laravel itself. So we don't need to define it manually.Bolten
setting $casts is not working for me, it's coming back as string still.Colewort

© 2022 - 2024 — McMap. All rights reserved.