Home / Snippets / How to Set Timestamp Column to the Current Timestamp In Laravel 8 Migrations?
How to Set Timestamp Column to the Current Timestamp In Laravel 8 Migrations? cover

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

4.1K

3 years ago

0 comments

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();
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this