Laravel Eloquent - date attributes not being retrieved as Carbon objects

10,328

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

Share:
10,328
Germán Medaglia
Author by

Germán Medaglia

Updated on July 25, 2022

Comments

  • Germán Medaglia
    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 and updated_at properties.

    Any ideas what could be happening? I'm using TIMESTAMPS fields on a MySQL DB and Laravel version is 5.2.

  • ceejayoz
    ceejayoz about 8 years
    IMO, this is a kludgy workaround for something that should be fixed properly.
  • ceejayoz
    ceejayoz about 8 years
    There's an easier way. $this->start->format(...) in your accessors. I'd also suggest naming your accessors differently (like formattedStart or something), so you can still use the $this->start Carbon object in code.
  • sanky
    sanky about 4 years
    Ideally, it should work with setting $casts array but this seems to be broken for years now :(. This is the only workaround by using accessors.