Germán Medaglia
Germán Medaglia

Reputation: 182

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.

Upvotes: 9

Views: 12236

Answers (3)

Robin Dirksen
Robin Dirksen

Reputation: 3422

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

Upvotes: 5

Germán Medaglia
Germán Medaglia

Reputation: 182

Thanks for your help, @smartrahat and @user2094178. I was wrong, the attributes are actually being retrieved as Carbon objects. I was confused, because I was getting an error when trying to use these accessors for formatting my dates:

public function getStartAttribute($value)
{
    return $value->format('d/m/Y');
}

public function getEndAttribute($value)
{
    return $value->format('d/m/Y');
}

It seems at that point the values are already casted to strings (ie I can't use the Carbon::format() method). So I finally went with this approach:

public function getStartAttribute($value)
{
    return Carbon::parse($value)->format('d/m/Y');
}

public function getEndAttribute($value)
{
    return Carbon::parse($value)->format('d/m/Y');
}

Thanks again!

Upvotes: 0

smartrahat
smartrahat

Reputation: 5609

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.

Upvotes: 7

Related Questions