LARAVEL

Laravel Timestamps


In Laravel, the Eloquent ORM provides built-in support for automatically maintaining timestamp columns in your database tables. Timestamps are commonly used to track when a record was created (created_at) and when it was last updated (updated_at). Laravel's Eloquent automatically manages these columns, making it easy to keep track of the creation and modification times of your records.

 

Enabling Timestamps:

By default, Eloquent assumes that your tables have created_at and updated_at timestamp columns. To enable timestamps for a specific model, you need to add the $timestamps property to your model and set it to true.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = true;
}

 

Timestamp Format:

Laravel uses the Carbon PHP library to handle timestamps, which provides a convenient and expressive way to work with dates and times in PHP. When you retrieve timestamps from the database, they are automatically converted to Carbon instances, allowing you to easily manipulate and format them.

 

Automatic Timestamps:

When you create a new record using Eloquent's create() method, the created_at and updated_at timestamps will automatically be set for you. Similarly, when you update an existing record using Eloquent's save() method, the updated_at timestamp will be automatically updated.

 

Custom Timestamp Columns:

If your table uses different column names for timestamps, you can customize them in your model by overriding the default constants:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'creation_date';

    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'last_update';
}

 

Disabling Timestamps:

If you don't want Eloquent to automatically manage timestamps for a specific model, you can disable them by setting the $timestamps property to false.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

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

 

NOTE:

Laravel's built-in support for timestamps simplifies the process of tracking record creation and modification times in your database tables. By enabling timestamps in your models, you can easily keep track of when records were created and updated, which is useful for auditing, versioning, and other purposes.


LARAVEL