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.

8 comments:

  1. I like your post very much. It is very much useful for my research. I hope you to share more info about this. Keep posting ruby on rails online training hyderabad

    ReplyDelete
  2. Elevate your online presence with powerful dedicated server frankfurt.. Explore our Frankfurt options for global reach. Experience unmatched performance and reliability for your business needs.

    ReplyDelete
  3. A Dedicated Server is a physical server that's assigned to a single organization.

    ReplyDelete
  4. Escape to a luxurious best resort in jaipur, where royal elegance meets modern comfort. Enjoy world-class amenities, serene landscapes, and unforgettable experiences.

    ReplyDelete