Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent - date attributes not being retrieved as Carbon objects

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.

like image 579
Germán Medaglia Avatar asked Mar 15 '16 21:03

Germán Medaglia


2 Answers

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.

like image 151
smartrahat Avatar answered Sep 28 '22 04:09

smartrahat


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

like image 25
Robin Dirksen Avatar answered Sep 28 '22 05:09

Robin Dirksen