How to update timestamp in Laravel


In laravel usually you have created_at and updated_at field in your database table, these are timestamps() that you define in your laravel migration, the question is how to update the value of these timestamp specially the updated_at?

The created_at is set when you first insert the record after you run the save() method, so you probably don't want to change the value of created_at, but on the other hand the updated_at is updated when you updating one of the fields in the table.

Note that if none of the field is updated, even if you run the save method, the updated_at timestamp won't be updated.

The code below won't work:
$car = Car::find(1);                
$car->save();                       // this will not update the updated_at timestamp
But this code below is working:
$car = Car::find(1);                
$car->manufacture = 'Honda';
$car->save();                      // this will update the updated_at timestamp

The solution is to use the touch() method.
$car = Car::find(1);
$car->touch();                    // this will update the updated_at timestamp

So run the laravel touch() method to update the updated_at timestamp even if you are not changing any fields at all.


EmoticonEmoticon