user8555937
user8555937

Reputation: 2387

Laravel: prevent updated_at from filling on record creation

In recent versions of Laravel >=5.8 I've noticed when you create a new model record, the column updated_at from table is filled automatically with the same value as created_at. While it makes sense to fill in created_at on Model::create() what's the point of filling updated_at as well? In my view it would make more sense to leave it NULL as it was before Laravel 5.8

Is there a known easy way to disable this new behaviour?

Upvotes: 3

Views: 2438

Answers (2)

Cameron
Cameron

Reputation: 554

Technically, if it was created, it was also the last time the model was updated. It's default Laravel behavior. You can disable it and write your own on create / update methods for your model if you prefer. However I would keep it and question why it's causing a problem with your logic/ functionality.

//your model
public $timestamps = false;

// boot
static::creating( function ($model) {
    $model->setCreatedAt($model->freshTimestamp());
});

//static::updating() .... and so on

Upvotes: 2

halloei
halloei

Reputation: 2036

I personally prefer the current behaviour with updated_at set to the current timestamp on creation. In that way, the unmodified records will be placed between the modified ones when sorting by updated_at.
If the initial value of updated_at was null, they would be placed either on the beginning or the end of the list. I don't think that's what most people want.

However, you may change that in the model's class:

protected static function booted(): void
{
    static::creating(function (self $model) {
        $model->updated_at = null;
    });
}

Upvotes: 6

Related Questions