If you have an existing table in the database and you are working with the Laravel Migration system. Here is how you can add a new migration to add timestamps field i.e. created_at and updated_at fields to the table.

Let's say you are working with table named transactions.

Run the following command to generate a new migration file.


php artisan make:migration add_timestamps_to_transactions_table

This will create a new file named add_timestamps_to_transactions_table prepend by the current timestamp to the database > migrations folder.

You can now use the timestamps method in the callback function to generate the timestamps in the up method, and use the dropTimestamps method in the down method to rollback the changes.


    public function up()
    {
        Schema::table('tbl_Transactions', function (Blueprint $table) {
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('transactions', function (Blueprint $table) {
            $table->dropTimestamps();
        });
    }

If you have a project where you are also using Query building or other ways to insert data into the table, you might want to ave default values in the timestamps date. You can do this by adding default value option in the migration itself.


public function up()
{
Schema::table('tbl_Transactions', function (Blueprint $table) {
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();
});
}

Note : All the existing records in the database will be updated with the current timestamp in the created_at and updated_at columns. Avoid this if you are not looking to update the existing records.

Comments