Home / Snippets / How to Update Laravel Model Without Touching Timestamps
How to Update Laravel Model Without Touching Timestamps cover

How to Update Laravel Model Without Touching Timestamps

9.8K

3 years ago

0 comments

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
}
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this