1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravelのmigrationでtimestamps()を使用するとデフォルト値が設定できない場合の対処法

Last updated at Posted at 2022-03-09

概要

timestamps()初期値がNULLになったままのコードをリファクタリングした際の知見を残します

<?php
Schema::create('training_groups', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->timestamps();
});

対策

以下を利用することで毎回created_atupdated_atに現在時刻を入力するコードを消し去りました。

$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

// or 
// laravel8.x以降
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?