0
0
Laravelframework~5 mins

Timestamps management in Laravel

Choose your learning style9 modes available
Introduction

Timestamps management helps you automatically track when records are created or updated in your database. This makes it easy to know the history of your data without extra work.

When you want to know when a user signed up or last updated their profile.
When you need to track when a blog post was published or edited.
When you want to keep a log of changes in orders or transactions.
When you want to sort records by creation or update time.
When you want to automatically manage these times without writing extra code.
Syntax
Laravel
class ModelName extends Model {
    public $timestamps = true;
}

By default, Laravel models have timestamps enabled.

The timestamps use two columns: created_at and updated_at.

Examples
This model will automatically fill created_at and updated_at columns.
Laravel
class Post extends Model {
    // timestamps are enabled by default
}
This disables automatic timestamps for this model.
Laravel
class Comment extends Model {
    public $timestamps = false;
}
This creates created_at and updated_at columns in the database table.
Laravel
Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->timestamps();
});
Sample Program

This example shows a Laravel model with timestamps enabled by default. When you save a new task, Laravel sets created_at and updated_at. When you update the task, only updated_at changes automatically.

Laravel
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    // timestamps enabled by default
}

// Usage example in a controller or tinker:
// Creating a new task
$task = new Task();
$task->name = 'Learn Laravel timestamps';
$task->save();

// The created_at and updated_at fields are set automatically

// Later, updating the task
$task->name = 'Master Laravel timestamps';
$task->save();

// The updated_at field updates automatically

// To see timestamps:
return [
    'created_at' => $task->created_at->toDateTimeString(),
    'updated_at' => $task->updated_at->toDateTimeString(),
];
OutputSuccess
Important Notes

You can customize the timestamp column names by overriding const CREATED_AT and const UPDATED_AT in your model.

If you disable timestamps, you must manage these columns manually if needed.

Laravel uses Carbon instances for timestamps, so you can format dates easily.

Summary

Timestamps track when records are created and updated automatically.

Enable timestamps by default or disable with $timestamps = false.

Use $table->timestamps() in migrations to add timestamp columns.