Sunday, December 30, 2018

Set the Current Timestamp as the Default Value of A Timestamp Column in A Table with Laravel Migrations

Set the Current Timestamp as the Default Value of A Timestamp Column in A Table with Laravel Migrations

How to Set the current timestamp as the default value of a timestamp column in a table with Laravel migrations? Let’s find out:

SQL Statement

Use DEFAULT CURRENT_TIMESTAMP.

CREATE TABLE `products` (
         :
  `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
         :
) 

Laravel Migrations

Just use a raw expression, DB::raw() to set CURRENT_TIMESTAMP as a default value for a column:

$table->timestamp('created_at')
      ->default(DB::raw('CURRENT_TIMESTAMP'));

This works for every database driver.

6 comments: