LoginSignup
3
3

More than 3 years have passed since last update.

Laravelでテーブルのcreated_at, updated_atに時刻をミリ秒単位で入れる

Posted at

初めに

PHP(laravel)の開発で、
データベースにinsertする際、created_at、updated_atの時刻を、ミリ秒(3桁)まで指定する要件があり、ネットで探しても良記事が見つからなかったのでメモ。

1.getDateFormat()をModelに記載

例として、productsテーブルに商品を登録するという想定。

Product.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model 
{
    //~省略~

    //この関数をモデルに追加
    public function getDateFormat()
    {
        return 'Y-m-d H:i:s.v';
    }
}

2.現在時刻をミリ秒単位に成型

コントローラにDBの処理を書くことはバットプラクティスかもしれませんが、
今回簡単な例としてコントローラーに下記のように記述。
*Carbonを使用。
(PHP7.2以降であればdate()->format('Y-m-d H:i:s.v')でもミリ秒に変換できるみたいです)

ProductController.php

//carbonを利用
use Carbon\Carbon;

function createProduct ($product)
{
    //現在時刻をミリ秒に変更("2020-08-04 12:45:07.105"のような形式になる)
    $now = Carbon::now()->format('Y-m-d H:i:s.v');

    $products = new Product();
    //~略~
    $products->created_at = $now;
    $products->updated_at = $now;
    $products->save()
}

これでcreated_at、updated_atからむに現在時刻がミリ秒の単位で登録される。

参考

https://stackoverflow.com/questions/50208932/laravel-model-trailing-data-when-save-the-model
https://hnw.hatenablog.com/entry/20180401

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