Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent Dirty Checking Carbon Dates

I have a published_at field in my model that I setup as a carbon date.

class Model {

    protected $dates = ['published_at'];

    ....

    public function setPublishedAtAttribute($val)
    {
         $this->attributes['published_at'] = \Carbon\Carbon::createFromTimeStamp(strtotime($val));
    }
}

This is a filed settable by the user. When I run a dirty check on it:

$article->fill($data);
echo $article->isDirty() ? 'true' : 'false';

It always comes up dirty. Am I doing something wrong or is this because it's trying to compare two Carbon objects?

like image 424
Rob Avatar asked Dec 05 '25 11:12

Rob


1 Answers

This is now fixed with Laravel 5.5.

For everyone using an older Laravel version:

Just overwrite your getDirty() method like this:

public function getDirty()
{
    $dirty = parent::getDirty();

    foreach ($dirty as $key => $value) {
        if (!array_key_exists($key, $this->original)) {
            continue;
        }

        // unset any non-changed date values
        if ($this->isDateAttribute($key)) {
            $old = new Carbon($this->original[$key]);
            $new = new Carbon($value);

            if ($old->eq($new)) {
                unset($dirty[$key]);
            }
        }
    }

    return $dirty;
}
like image 89
Johannes N. Avatar answered Dec 08 '25 01:12

Johannes N.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!