Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Set the Default Value of a DATE Column to the Current date with Laravel Migrations?

I'm having some issues with creating a migration, one of the columns I have on the table is a DATE type, not DATETIME or TIMESTAMPS. And the problem is that I can't find a way to define the default value for this column, I've tried the following:

$table->date('request_date')->default(Carbon::now());
//This uses the date the migration was created as a default, not the current date.

$table->date('request_date')->default(DB::raw('CURRENT_DATE()'));

$table->date('request_date')->default(DB::raw('date(now())'));

$table->date('request_date')->default(DB::raw('CURRENT_DATE'));

And using the DB:raw is giving me an error:

SQLSTATE[42000]: Syntax error or access violation: Doctrine\DBAL\Driver\PDO\Exception::("SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CURRENT_DATE() after issue_date, add expiry_date date null after `request_da' at line 1")

Any recommendation would be appreciated, thanks!

like image 370
E. Galdamez Avatar asked Nov 18 '25 11:11

E. Galdamez


1 Answers

in MySQL, you can not set default to current date. In your case, you can use request_date as a TIMESTAMP fields, and in your model, you cast it to date format.

$table->timestamp('request_date')->useCurrent()

And in your model:

protected $casts = [
    'request_date' => 'datetime:Y-m-d',
];

This way is much more flexible. If in the future, you need to get the time, you still can do it

like image 154
Khang Tran Avatar answered Nov 20 '25 05:11

Khang Tran