skip to Main Content

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: DoctrineDBALDriverPDOException::("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!

2

Answers


  1. DATETIME or TIMESTAMP type only offers automatic initialization to the current date From mysql doc, so you can able to use Laravel Observer with creating() method to set current date.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search