Hassan Saqib
Hassan Saqib

Reputation: 2757

Custom Timestamps in Laravel

I want to keep the time record of changes in certain columns of my table. How can I get and save timestamp values in db? I am trying to do it in following way but getting always 0000-00-00 00:00:00 in col_edited_at column.

$case->col_edited_at = time();
$case->save();

Upvotes: 0

Views: 6040

Answers (3)

lukasgeiter
lukasgeiter

Reputation: 152860

The other answers are correct but I have an idea of a more elegant solution. So you don't have to think about setting the timestamp anymore. Add this to your model and if you change the column it will refresh the col_edited_at field:

public static function boot(){
    parent::boot();

    static::saving(function($model){
        if($model->isDirty('col')){
            $model->col_edited_at = Carbon::now();
        }
    });
}

So when the model is getting saved and col is dirty (meaning it has changed) the timestamp will be set to the current time.

Usage:

$model = MyModel::find(1);
$model->col = 'foo';
$model->save();

Upvotes: 6

Md. Sahadat Hossain
Md. Sahadat Hossain

Reputation: 3236

simply use

date('Y-m-d H:i:s') instead of time()

Upvotes: 1

Joe
Joe

Reputation: 4728

MySQL timestamp fields by default require the format 0000-00-00 00:00:00. If you're just wanting to store a unix style "seconds since the epoch" timestamp like that returned by time() use an integer field, or else use:

$case->col_edited_at = date('Y-m-d H:i:s');
$case->save();

Upvotes: 2

Related Questions