40
42

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 3 years have passed since last update.

Laravel のマイグレーションで created_atとupdated_atのデフォルトを設定する

Last updated at Posted at 2019-11-14

多少考えたので、メモとして残しておきます
5.2以降対応のはずです

下記のようなマイグレーションがあるとします。


 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 100)->index()->comment('名前');
            $table->timestamps();
            $table->softDeletes();
        });
    }

timestamps()

NULL値可能なcreated_atとupdated_atカラム追加

と二つのカラムを生成します。

実装を見ると、まんま呼び出しているだけです

vendor\laravel\framework\src\Illuminate\Database\Schema\Blueprint.php

/**
     * Add nullable creation and update timestamps to the table.
     *
     * @param  int  $precision
     * @return void
     */
    public function timestamps($precision = 0)
    {
        $this->timestamp('created_at', $precision)->nullable();

        $this->timestamp('updated_at', $precision)->nullable();
    }


'timestamp'に現在時刻をデフォルトを設定する
useCurrent()があります。

上記の通りvoidなので、繋げられません。
Call to a member function useCurrent() on nullとエラーが出ます。

なので、下記のように二つに分けて設定しましょう


 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 100)->index()->comment('名前');
            $table->timestamp('updated_at')->useCurrent()->nullable();
            $table->timestamp('created_at')->useCurrent()->nullable();
            $table->softDeletes();
        });
    }

40
42
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
40
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?