How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

Cover Image for How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

How to Set the Default Value of a Timestamp Column in Laravel Migrations

šŸ“· by Clay Banks on Unsplash

So you want to set the default value of a timestamp column to the current timestamp using Laravel Migrations? You're not alone! Many developers face this challenge when working with Laravel's powerful Schema Builder.

In this blog post, we'll address this common issue, provide easy solutions, and get you up and running in no time. Let's dive in!

The Problem

As you may have noticed, the timestamps() function in Laravel sets default values of 0000-00-00 00:00 for both created_at and updated_at columns. But what if you need the columns to default to the current timestamp when a record is created or updated? You're in luck, because there are a couple of straightforward ways to achieve this.

Solution 1: Modifying the Migration File

The first solution involves modifying the migration file itself. Open the migration file that corresponds to your desired table and locate the timestamps() function call. By default, it looks like this:

$table->timestamps();

To set the default values to the current timestamp, you can manually modify the created_at and updated_at columns during the creation of the table. To do this, replace the timestamps() function call with the following code:

$table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(\DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

With this modification, the created_at column will default to the current timestamp when a record is created, and the updated_at column will be updated to the current timestamp whenever a record is updated.

Solution 2: Modifying the Model

The second solution involves modifying the corresponding model to automatically set the default values when a new record is created or updated. Laravel provides a convenient way to do this using Eloquent's bootable trait functionality.

Open the model file associated with your table and add the following code to the class:

use Illuminate\Database\Eloquent\Model;

class YourModel extends Model
{
    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->created_at = $model->freshTimestamp();
            $model->updated_at = $model->freshTimestamp();
        });

        static::updating(function ($model) {
            $model->updated_at = $model->freshTimestamp();
        });
    }
}

With this modification, the created_at and updated_at columns will automatically be set to the current timestamp whenever a new record is being created or updated.

Conclusion

Setting the default value of a timestamp column to the current timestamp with Laravel Migrations doesn't have to be a headache. With the solutions provided in this blog post, you can easily achieve the desired behavior.

Whether you choose to modify the migration file or the model, make sure to select the solution that best fits your project's needs.

Now it's your turn! Have you faced any challenges when setting default values for timestamp columns in Laravel? How did you handle them? Share your experiences in the comments below!

šŸ‘‡šŸ‘‡šŸ‘‡


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

šŸ”„ šŸ’» šŸ†’ Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! šŸš€ Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings šŸ’„āœ‚ļø Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide šŸš€ So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? šŸ¤” Well, my

Matheus Mello
Matheus Mello