Laravel Model Timestamps without an updated_at

Laravel makes it easy to add created_at and updated_at fields to your models. Just include the ->timestamps() shorthand in the migration, and use public $timestamps = true on the model.

Sometimes though you’ll have high-volume models such as an event log that record immutable things that will never be updated. Storing a redundant updated_at can be a bit wasteful if you’ll never need it, and it tells you nothing new.

It’s easy to customise the behaviour, but perhaps a little hard to discover. I missed it in my searching until Jess Archer told me it was supported.

In the migration

Define your migration like so:

<?php
// ...

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('my_table', function(Blueprint $table) {
            $table->smallIncrements('id');
            $table->timestamp('created_at', 0)->nullable();
            // define created_at on its own
        });
    }
}

In the model

By default Laravel will attempt to write to the updated_at column. If you don’t have one it will error.

You can easily disable it like so:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    public $timestamps = true;

    const UPDATED_AT = null;

    //...
}

Done 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *