0
0

More than 3 years have passed since last update.

LaravelでDBにデータを保存する際、created_atなどが自動で入らなかった時の対策

Posted at

状況

Laravelで開発を行っていた際に、DBにデータを保存しようと試みたのですが、created_atなど自動で登録して欲しいデータがnullになってしまったため、どうしようかと考えました。

行った対策(ダメだった、あまり良くない)

できたけどあまりよろしくないコード

$result = Model::insert([
  // 中略
  'updated_by_user_id' => $user->id,
  'created_by_user_id' => $user->id
}

そもそも本来は入力をせず、自動で登録して欲しい。

行った対策(できたもの)

他との都合でinsertを使用して直接値を登録していましたが、しっかりとインスタンスを作成してからsave()メソッドを使ってみました。

$result = new Model();
// 中略
$result->save();

結果、無事に登録されました!

参考にさせていただきました。ありがとうございました!
https://qiita.com/katsunory/items/87a73297f44a65f1474f

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