Search code examples
mysqllaravellaravel-5laravel-5.3

Laravel: MySQL auto-updates my updated_at field everyday without any update on article


I recently worked on a blog application using Laravel 5.4 on my localhost and everything was working fine. However, when I uploaded my application on a remote server on the internet, the updated_at field on every post kept updating automatically every day.

The same code when run on my local machine works fine and the updated_at field is only updated when the post is updated. I am guessing that the problem is at the level of the database configuration but I have no idea how to fix that.

The source code: migrations

Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->string('featured_image');
    $table->string('slug')->unique();
    $table->text('body');
    $table->boolean('published')->default(false);
    $table->unsignedInteger('user_id');
    $table->integer('views')->default(0);
    $table->timestamps();
    $table->softDeletes();

    $table->foreign('user_id')->references('id')->on('users');
});

and I have this in my model Post.php:

    protected $dates = ['created_at', 'updated_at', 'deleted_at'];

I am only adding the source code for the benefit of the doubt because it is the same source code that runs on my localhost and produces the desired result.


Solution

  • It is because your views field get updated for each view by users.

    You can disable updating timestamp fields before increasing view :

    $obj->timestamps = false;
    $obj->views += 1;
    $obj->save();