IsraelOrtuno / Eavquent

EAV modeling package for Laravel and Eloquent – This package is abandoned, please use this fork https://github.com/rinvex/attributes
63 stars 13 forks source link

Model mutators for custom attributes #45

Closed breaktag closed 6 years ago

breaktag commented 8 years ago

Hello,

I have been using Eavquent a few weeks now and actually really liking it. I have come across an issue which I have managed to fixed but it is definitely not the best way. I am looking for a more robust solution.

I have a DateTime attribute, and the front end displays and submits the date in this format: DD/MM/YYYY. When saving/updating with eloquent I can usually use the $dates property to specify a datetime field. Or I can use a mutator method in my model setMyCustomDateAttribute() to parse into a Carbon date format.

My app breaks (without an error) when trying to save/update a string DD/MM/YYYY. I can't specify custom attributes as a date format nor can I use a mutator. My current solution is this in the extending Datetime class inside the package:

namespace Devio\Eavquent\Value\Data;

use Devio\Eavquent\Value\Value;

class Datetime extends Value
{
    /**
     * Casting content to date.
     *
     * @var array
     */
    protected $dates = ['content'];

    /**
     * Set the content.
     *
     * @param $content
     * @return mixed
     */
    public function setContent($content)
    {
        $content = \Carbon\Carbon::createFromFormat('d/m/Y', $content)->toDateTimeString();
        return $this->setAttribute('content', $content);
    }
}

In my situation I could just use a Varchar type but I thought I would be a bit more elegant. Also the above example fails, when I have a datetime which needs to be in a different format.

Cheers

breaktag commented 8 years ago

The same also applies with an accessor as well to parse it back from a DateTime format to a display format.

IsraelOrtuno commented 8 years ago

Can you share your code so I can reproduce?