Search code examples
laravelmutators

Laravel Mutators, Accessors


I've tried to implement mutators into my laravel 5.5. project since it looks like this would be the best way to auto-convert date object but for some reason it's not working. What i try to accomplish is to load a date object from mysql format Y-m-d and convert it to d.m.Y and write date objects with a format of d.m.Y to mysql with the format of Y-m-d. I get constantly errors like "delimiter not found" or "format error" etc.

protected $dateFormat = 'Y-m-d h:i';
protected $dates = [
    'joined',

];

function getJoinedAttribute()
{
    return $this->attributes['joined']->format('d.m.Y');
}

function setJoinedAttribute()
{
    return $this->attributes['joined']->format('Y-m-d');
}

Solution

  • You sould use Carbon library to convert date.

    Like this :

     public function getDobAttribute($value)
        {
            return Carbon::parse($value)->format('d/m/Y');
        }
    
        public function setDobAttribute($value)
        {
            $this->attributes['dob'] = Carbon::createFromFormat('d/m/Y', $value)->toDateString();
        }