Mar 15, 2017
0
Level 2
Defining Date Mutator for a Date instead of Datetime
Hello, I have a field on my User model which is defined as a date, and I would like when it is serialized to output a date, and not a datetime. Refer to my hire_date field:
$ php artisan tinker
Psy Shell v0.8.2 (PHP 7.1.1 — cli) by Justin Hileman
>>> $user = User::find(1);
=> User {#772
id: 1,
first_name: "Nils",
last_name: "Predovic",
hire_date: "1980-08-13", // OK
created_at: "2017-03-10 20:23:37",
updated_at: "2017-03-10 20:23:37",
}
>>> $user->hire_date
=> Carbon\Carbon {#738 // OK
+"date": "1980-08-13 00:00:00.000000",
+"timezone_type": 3,
+"timezone": "UTC",
}
>>> $user->toArray()
=> [
"id" => 1,
"first_name" => "Nils",
"last_name" => "Predovic",
"hire_date" => "1980-08-13 00:00:00", // Would like to be '1980-08-13'
"created_at" => "2017-03-10 20:23:37",
"updated_at" => "2017-03-10 20:23:37",
]
>>>
I understand from the docs that fields defined as a date on the model are returned as Carbon instances, and are then serialized in a timestamp format, but I would like to override this when I have an explicit date field, and not datetime.
What I've come up with is to set an accessor for the field and reparse the date:
public function getHireDateAttribute($hire_date)
{
return Carbon::parse($hire_date)->toDateString();
}
but I'm wondering if there is a better way. Thank you.
Please or to participate in this conversation.