Posts Learn Components Snippets Categories Tags Tools new About
/

How to Set Timestamp Column to the Current Timestamp In Laravel 8 Migrations?

Learn how to set the timestamp columns (published_at or added_at) column to the current timestamp in laravel 8 through the migration file.

Created on Oct 22, 2021

36 views

To set the default timestamps you can specify the "default()" method and using "DB::raw()" to get the CURRENT_TIMESTAMP value. This method works across different database drivers MySQL, PostgreSQL and others.

Using DB::raw("CURRENT_TIMESTAMP")


To set the CURRENT_TIMESTAMP you can call it within the DB::raw() method like below.
<?php

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

Using useCurrent


Another approach is also using the "useCurrent()" method and this will set the default value to the CURRENT_TIMESTAMP.
<?php

/* For Create */
$table->timestamp('created_at')->useCurrent();

/* For Update */
$table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)