DisableUpdatedAt Trait for Laravel 5.4

Published: 2017-07-29

Update 2017-09-16: I've released a small package containing the mentioned trait below. You can find installation instructions on Github.


I'm currently working on a project where we rewrite an old CodeIgniter Application in Laravel. Unfortunately, the database behind the application can't be changed and not all tables have a created_at and an updated_at column.
This table structure creates issues when you update the data with Eloquent. You would see error messages like: "Can't update $table because updated_at column does not exist."

You can disable all timestamps (created_at and updated_at) by setting a public $timestamps = false property in your models. But if you want just to disable the updated_at column you have to work around the Eloquent Builder class 1.

I've written the following PHP Trait which sets $timestamps = false before it executes the update query and resets to $timestamps = true after the query has been executed.

If you want to use it in your project just create a DisableUpdatedAt.php file in App/Traits and use it in your models like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\DisableUpdatedAt;

class Page extends Model
{
    use DisableUpdatedAt;

}

  1. update and addUpdatedAtColumn are the methods which cause the issue. When performing an update, Laravel always appends the updated_at column to the query. 

Questions?

Have a question about this post or anything else?