DisableUpdatedAt Trait for Laravel

• 1 min read
Update 16.09.2017

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.

namespace App\Traits;

/**
 * This Trait disabled the updated_at value for a model.
 * Laravel doesn't provide an easy way to to this.
 * The framework **alyways** tries to append the updated_at column
 * when the `$timestamps` property is not set to false.
 * See code here: https://github.com/illuminate/database/blob/5.4/Eloquent/Builder.php#L757-L760.
 *
 * This traits disables all timestamps (including created_at) when performing
 * an update. We do this by listening to the `updating` and `updated`
 * events.
 */
trait DisableUpdatedAt
{
    protected static function boot()
    {
        parent::boot();

        static::updating(function ($model) {
            $model->timestamps = false;
        });
        static::updated(function ($model) {
            $model->timestamps = true;
        });
    }

    public function setUpdatedAt($value)
    {
        //
    }

    public function getUpdatedAtColumn()
    {
        return '';
    }
}

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:

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.