LoginSignup
0
0

LaravelとMySQLを組み合わせて開発を行った際、タイムスタンプが正しく記録されないという問題に遭遇しました。
この記事は解決までの記録です。

問題の発生

マイグレーションファイルを以下のように書きました。

Schema::create('cat_chan', function (Blueprint $table) {
   $table->id();
   $table->string('title');
   $table->text('content');
   $table->timestamps(); // created_atとupdated_atのカラムが自動的に追加される
}); 

しかし、データを入れた際created_atupdated_atの値がnullになっていました。

解決方法

created_atupdated_atを別々に書いて->useCurrent()を書き足すことで、現在の時刻を自動的に記録させることができました。

Schema::create('cat_chan', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->timestamp('created_at')->useCurrent();//変更
    $table->timestamp('updated_at')->useCurrent();//変更
});

まとめ

useCurrent()を使用することで、データを挿入するたび、現在時刻が記録されるようになりました。
めでたし!

0
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
0
0