LoginSignup
0
0

More than 1 year has passed since last update.

LaravelのEloquentでtoArrayを使う場合はタイムゾーン設定が反映されないことがある

Posted at

結論

Eloquentのattributeが、config/app.phpのtimezoneの設定が反映されずにUTCで取得されることがあります。
この条件は下記の通りです。

  • toArrayまたはtoJson呼び出し時
  • $castsプロパティにてdatetimeへのキャストが設定されているattribute

必要に応じてModelクラスのオーバーライドなど対策を行いましょう。

環境など

Laravel9系

理由

$castsにてdatetimeへキャストを設定したattributeをjsonserializeする際、CarbonのtoJsonメソッドが呼ばれます。
このメソッドは必ずUTCの値を返すため、結果としてEloquentのtoArrayやtoJsonメソッドの結果もUTCになってしまいます。

CarbonのtoJsonを呼び出している箇所: \Illuminate\Database\Eloquent\Concerns\HasAttributes::serializeDate

対策例

\Illuminate\Database\Eloquent\Concerns\HasAttributes::serializeDateメソッドを任意の形式で返却するようオーバーライドしましょう。

    protected function serializeDate(DateTimeInterface $date): string
    {
        return $date->format(DateTimeInterface::RFC3339);
    }
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