Laravel Eloquent - date attributes not being retrieved as Carbon objects
Solution 1
Try this code in your model:
public function getStartAttribute($date)
{
return Carbon::parse($date);
}
public function getEndAttribute($date)
{
return Carbon::parse($date);
}
The convention here is first write get
then field name and attribute
. They should write together in camel case. So, in your case the method name become getStartAttribute
and getEndAttribute
.
Solution 2
You can use this if the table are in the User model (can be something else like News),
$user = User::find($id);
dump($user->start->format('Y-m-d');
This will dump the start column and format it to Y-m-d.
There is also a way to achieve this with te following, it will convert the start
column for the database to a Carbon object and return it as start_date
or startDate
or StartDate
:
public function getStartDateAttribute() {
return Carbon::parse($this->start);
}
You can also look at the Laravel documentation: https://laravel.com/docs/5.2/eloquent-mutators#date-mutators
Germán Medaglia
Updated on July 25, 2022Comments
-
Germán Medaglia almost 2 years
I've got my
$dates
attribute on a Quota Eloquent model like this:protected $dates = ['start', 'end'];
When retrieving data from the DB, those fields are not being set as Carbon instances, but strings instead. Same happens to
created_at
andupdated_at
properties.Any ideas what could be happening? I'm using TIMESTAMPS fields on a MySQL DB and Laravel version is 5.2.
-
ceejayoz about 8 yearsIMO, this is a kludgy workaround for something that should be fixed properly.
-
ceejayoz about 8 yearsThere's an easier way.
$this->start->format(...)
in your accessors. I'd also suggest naming your accessors differently (likeformattedStart
or something), so you can still use the$this->start
Carbon object in code. -
sanky about 4 yearsIdeally, it should work with setting $casts array but this seems to be broken for years now :(. This is the only workaround by using accessors.