1

If I run this in a migration script, there are no issues:

Schema::create('cancel_requests', function (Blueprint $table) {
  $table->id();
  $table->timestamp('date')->index();
});

But the moment I add another timestamp:

Schema::create('cancel_requests', function (Blueprint $table) {
  $table->id();
  $table->timestamp('date')->index();
  $table->timestamp('created_at')->index();
});

Now I get this error:

QLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'created_at'

I can see the sql being generated as:

create table `cancel_requests` 
  (
    `id` bigint unsigned not null auto_increment primary key, 
    `date` timestamp not null, 
    `created_at` timestamp not null
  ) default character set utf8mb4 collate 'utf8mb4_unicode_ci'

Can someone please explain to me why this is failing when the "date" field has no issue and the sql being generated does not look incorrect?

rockstardev
  • 13,479
  • 39
  • 164
  • 296

1 Answers1

1

You can just write $table->timestamps(); at the end of create like:

Schema::create('cancel_requests', function (Blueprint $table) {
  $table->id();
  $table->timestamp('date')->index();
  $table->timestamps();
});

It will create you created_at and updated_at fields with desired value.

Check out

You have to define default value for created_at column in your situation like:

$table->timestamp('created_at')->useCurrent()->index();

or

$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'))->index();
Vüsal Hüseynli
  • 889
  • 1
  • 4
  • 16
  • Thanks! That does solve it but it doesn't really answer my question. I want to know WHY my code fails, not how to make it work. – rockstardev Aug 03 '22 at 13:27