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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With