Sling Academy
Home/PHP/created_at and updated_at columns in Eloquent (Laravel)

created_at and updated_at columns in Eloquent (Laravel)

Last updated: January 16, 2024

Introduction

Laravel is a powerful and elegant PHP framework used by developers for web application development. One of the key features of Laravel is Eloquent, an object-relational mapper (ORM) that provides an ActiveRecord-style ORM for working with your database. A common feature when building web applications is to track when records are created and updated. Laravel provides this functionality out of the box with the created_at and updated_at timestamps.

Understanding Automatic Timestamps

By default, Eloquent expects created_at and updated_at columns to exist on your tables. These special columns are automatically managed by Laravel and are set to the current date and time when the record is created or updated.

To use these timestamps, ensure your migration includes these fields:

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('body');
    $table->timestamps();
});

The $table->timestamps(); method creates the created_at and updated_at columns for you.

Disabling Auto Timestamps

If you do not wish to have these columns automatically managed by Eloquent, you can disable this feature by setting the $timestamps property on your model to false:

class Post extends Model
{
    public $timestamps = false;
}

Overriding Timestamps Column Names

In some situations, you may want to override the default column names. You can do this by defining the const CREATED_AT and const UPDATED_AT in your model:

class Post extends Model
{
    const CREATED_AT = 'creation_date';
    const UPDATED_AT = 'last_modified_date';
}

This will instruct Eloquent to use creation_date and last_modified_date instead of the defaults.

Understanding the Model’s Touch Method

In addition to the automatic setting of timestamps, Eloquent also provides the touch method which updates the updated_at timestamp to the current time. This method does not require you to save the model:

$post = Post::find(1);
$post->touch();

This can be useful if you want to signal that a model has been updated without actually changing any of its visible attributes.

Customizing Timestamps

You may also control the format of your timestamps by overriding the DateFormat method on your Eloquent model:

class Post extends Model
{
    protected function getDateFormat()
    {
        return 'Y-m-d H:i:s.u';
    }
}

Keep in mind that this format must be compatible with your database’s date and time type.

Using Timestamps in Queries

Timestamps can also be used in your Eloquent queries. For example, you might retrieve all posts updated in the last week:

$posts = Post::where('updated_at', '>', now()->subWeek())->get();

Timestamps in JSON Serialization

When you serialize models to JSON (perhaps for an API response), the created_at and updated_at fields are included by default using the ISO 8601 format. If you need to customize how these dates are serialized, you can use the serializeDate method:

class Post extends Model
{
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
}

Conclusion

Using created_at and updated_at effectively can help manage and track changes in your database records. Laravel’s Eloquent makes this easy with its built-in support. Whether you’re looking to leverage this feature, customize how it behaves, or handle JSON serialization, the process is straightforward and comprehensive within the framework. Remember that regardless of the approach you choose, Eloquent is designed to streamline your back-end development process while giving you complete control over your application’s database interactions.

An understanding of Eloquent’s timestamps is just a part of creating efficient, robust Laravel applications. Continue experimenting with Eloquent’s many features to build and maintain excellent web applications with ease.

Next Article: How to Format Date Time in Eloquent (Laravel)

Previous Article: Using UUID and ULID in Laravel Eloquent

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array