Thank you so much for this. So I have to directly specify on the model which fields are dates. I knew I could do this, because I've done it before. It was just hard to dig up the information again.
:)
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I am wondering if I can configure anything on my models or environment to allow setting a date field to an integer, and having Eloquent automatically interpret this as Unix time.
At the moment, it's a bit painful to use Carbon::createFromTimestamp($unixTime) everywhere. I would prefer just being able to set my date fields to Unix time, save, and have Eloquent handle the casting.
To be clear, I want the database type to be Timestamp, and be able to cast Unix time to a timestamp. I am seeing answers on other sites where users want to save Unix time in the database. I know how to achieve that functionality.
Migration:
Schema::create('tests', function (Blueprint $table) {
//...
$table->timestamp('test_date')->nullable();
});
Model:
class Test extends Model
{
//...
protected $dates = [
'test_date'
];
}
Tinker:
>>> $model = \App\Test::first();
=> App\Test {#3042
//...
test_date: null,
}
>>> $model->test_date = 1579183788;
=> 1579183788
>>> $model->save();
=> true
>>> $model->fresh();
=> App\Test {#3027
//...
test_date: "2020-01-16 14:09:48",
}
>>>
Please or to participate in this conversation.