DEV Community

Mahmoud Ramadan
Mahmoud Ramadan

Posted on

Using Custom Timestamp Columns in Laravel Eloquent

If you need to customize the column names for created_at and updated_at, you can do so at the database level.

/**
 * Run the migrations.
 */
public function up(): void
{
    Schema::create('items', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        // Custom timestamp columns
        $table->timestamp('created_on')->nullable();
        $table->timestamp('updated_on')->nullable();
    });
}
Enter fullscreen mode Exit fullscreen mode

After creating the table, attempting to create a new Item model will result in an exception because Eloquent expects the default created_at and updated_at columns.

You can resolve this in one of the following ways.

Option 1: Disable timestamps entirely

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;
}
Enter fullscreen mode Exit fullscreen mode

Option 2: Define custom timestamp column names (recommended)

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    /**
     * The name of the "created at" column.
     *
     * @var string|null
     */
    public const CREATED_AT = 'created_on';

    /**
     * The name of the "updated at" column.
     *
     * @var string|null
     */
    public const UPDATED_AT = 'updated_on';
}
Enter fullscreen mode Exit fullscreen mode

Learn more in the documentation.

🔬Discover more practical insights on:
https://github.com/digging-code-blog/community-tips

Top comments (0)