Laravel Migration Default Value Current Timestamp Tutorial

Jan 17, 2023 . Admin



Hi Dev,

This article discusses the Laravel migration's current timestamp default option. Let's discuss about Laravel migration's standard current timestamp. In this post, you'll find a simple illustration of the default value for the Laravel migration timestamp. I'll show you how to make the current timestamp the migration's default using Laravel. Here, create a straightforward example of the current timestamp default value for a migration.

Laravel migration provides a useCurrent() and default() where you can set the default value current timestamps of that column. here I will give you simple tow examples of how to add default current timestamps, boolean, current time, etc. you can easily set with laravel 6, laravel 7, laravel 8 and laravel 9 version

so let's see bellow simple examples:

Create Migration Command:
php artisan make:migration create_items_table	
Example 1: Using useCurrent()
database/migrations/2021_04_07_125911_create_items_table.php
<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->id();
            $table->string('title')->nullable();
            $table->text('body');
            $table->boolean('is_active');
            $table->timestamp('creation_date')->useCurrent();
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('items');
    }
}	

you can run the migration command:

php artisan migrate	
Example 2: Using CURRENT_TIMESTAMP database/migrations/2021_04_07_125911_create_items_table.php
<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use DB;
  
class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->id();
            $table->string('title')->nullable();
            $table->text('body');
            $table->boolean('is_active');
            $table->timestamp('creation_date')->default(DB::raw('CURRENT_TIMESTAMP'));;
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('items');
    }
}	

you can run the migration command:

php artisan migrate	

i hope it can help you...

#Laravel