Posts Learn Components new Snippets new Categories Tags About
/

How to Update Laravel Model Without Touching Timestamps

Learn how to update Laravel Model without touching/changing the created_at and updated_at column

Created on Sep 29, 2021

41 views

In this short snippet, you will learn how to update a Model without touching/chancing the timestamps (created_at and updated_at) columns.

Update Model Without Updating Timestamps


To prevent the "timestamps" from updating, you can specify the timestamps value to "false" when saving the model. Imagine you have a post model and you want to update the "title" of the record. By default, it will update the "updated_at" column to the time when the record is saved.
<?php

$post = Post::first();
$post->title = "Post Title 1 Updated";
$post->timestamps = false;
$post->save();
If you do prefer to use the "update()" method then the code will be as follows.
$post = Post::first();
$post->save([
    'title' => "Post Title 1 Updated",
    'timestamps' => false
]);

Update Multiple Model Without Updating Timestamps


To update multiple models without updating their timestamps then you can make use of the "where" statement.
<?php

Post::query()
    ->whereIn('id', [1, 2, 3])->update([
        'title' => 'Post 1, 2, 3 have the same title',
        'timestamps' => false
    ]);
This goes the sample for when using the "DB" facade.
<?php

DB::table('posts')->... // your conditions here

Specify For The Whole Model


To prevent the Model timestamp from being updated, you can also specify the $timestamps property to false for any of your Eloquent model classes. This will disable the timestamps for the particular model so that you won't have to specify each update manually.
<?php

namespace App\Models;

class Post extends Model {
    public $timestamps = false; // put this code
}
new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻