Set the default value of a date column in Phinx migrations

Hello,

I want to set the default of a date column to todays date using Phinx migrations.

I can use CURRENT_TIMESTAMP for datetime columns, but it doesn’t work for date columns. I have also tried CURRENT_DATE without success.

I’ve gone thru the documentation and cannot find an answer.

Is this possible using Phinx? I am using a MySQL database in my application.

Thanks, Dean.

Have you tried this?

'default' => \Phinx\Util\Literal::from('CURRENT_DATE()')

Yes, and it just throws an error when trying to create the table. I have tried a few different variations, but the generated SQL always adds in quotes around the (CURRENT_DATE) part that I need in the SQL.

Generated:

start_date DATE NOT NULL DEFAULT '(CURRENT_DATE)'

What I need:

start_date DATE NOT NULL DEFAULT (CURRENT_DATE)

->addColumn('mydate', 'date', [
    'default' => \Phinx\Util\Literal::from('CURRENT_DATE')
])

make sure to NOT have the () at the end of CURRENT_DATE

Yep, tried this as well. Result:

`start_date` DATE NOT NULL DEFAULT 'CURRENT_DATE',

Also tried this:

'default' => \Phinx\Util\Literal::from('(CURRENT_DATE)')

result:
start_date DATE NOT NULL DEFAULT '(CURRENT_DATE)'

the code i posted above worked for me on cakephp 4.6.5 with phinx 0.13.4

1 Like

I couldn’t get Literal to work on Cake 5.4.2

But using execute($sql) as a work-a-round allowed it to work.

public function change(): void
    {
        $table = $this->table('table_name');
        $table->addColumn('my_date', 'date', [
            'null' => false,
        ]);
        $table->create();

        $this->execute('ALTER TABLE table_name ALTER COLUMN my_date SET DEFAULT (CURRENT_DATE);');
    }

I am using 11.8.6-MariaDB-5ubuntu0.1 from Ubuntu

I found the issue. Use \Migrations\Db\Literal

->addColumn('mydate', 'date', [
    'default' => \Migrations\Db\Literal::from('(CURRENT_DATE)')
])