Laravel Migration Default Value Current Timestamp Example
Hey Artisan,
This post is focused on laravel migration default value current timestamp. letβs discuss about laravel migration default current timestamp. This tutorial will give you a simple example of laravel migration timestamp default value. Iβm going to show you about how to set default current timestamp in laravel migration. Here, Create a basic example of laravel migration default value current timestamp.
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, laravel 9, laravel 10 and laravel 11 version.
so let's see bellow simple examples:
Create Migration Command:
php artisan make:migration create_items_table
Example 1: using useCurrent() - Best Way
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');
}
}
Now, you can run migration:
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');
}
}
Now, you can run migration:
php artisan migrate
you can use as you need.
i hope it can help you...