How to Set Default Value Current Timestamp Using Laravel Migration?

Jan 17, 2023

.

Admin

How to Set Default Value Current Timestamp Using Laravel Migration?

Hi Dev,

The current timestamp default setting for Laravel migration is the subject of this article. Let's talk about the default current timestamp in Laravel migration. You'll get a straightforward example of the default setting for the Laravel migration timestamp in this article. I'll demonstrate how to set the current timestamp as the default in Laravel migration. Create a simple sample of a migration's current timestamp default value here.

You can set the default value for the column's current timestamps using the useCurrent() and default() functions provided by Laravel migration. Here, I'll show you how to add boolean, the current time, and default current timestamps using just two straightforward examples. With versions of Laravel 6, Laravel 7, Laravel 8, and Laravel 9, you may easily set.

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