--> -->

skimemo


skimemo - 日記/2022-05-14

_ LaravelでModelからのデータをtoArray()するとtimezoneがUTCになってしまう問題

_ 概要

タイトルのまんまです。
Modelからtimestamp型のデータを取得して、配列で扱おうと以下のように ->toArray()すると、日付がUTCになってしまいます。

  1
  2
  3
  4
  5
$result = Reservation::where('userid',1)
        ->orderBy('send_datetime','desc')
        ->limit(1)->get();
 
print_r($result->toArray()); 
[updated_at] => "2022-05-13T23:00:16.000000Z"

ほんとは

[updated_at] => 2022-05-14 08:00:16

になって欲しい。

もちろん、config/app.phpの timezone や、config/database.phpの timezone や、モデルのprotected $dates =の設定をしてもです。

_ 解決方法

  1. App\Models\Models を作成します
      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
    
    <?php
     
    namespace App\Models;
     
    use DateTimeInterface;
    use Illuminate\Database\Eloquent\Model;
     
    class Models extends Model {
     
        // タイムゾーンを適用するフィールド
        protected $dates = ['updated_at',];
     
        // toArray()したときに日付をUTCにしないためのoverride
        protected function serializeDate(DateTimeInterface $date): string {
            return $date->format('Y-m-d H:i:s');
        }
     
    }
  2. モデル側でこいつをextendsします
      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
    
    <?php
     
    namespace App\Models;
     
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Builder;
     
    class Reservation extends Models
    {
        use HasFactory;
        use Encryptable;
     
        /**
         * 予約一覧を取得
         * @return array
         */
        public function getReservationAll(): array {
            return Reservation::get()->toArray();
        }
    }
    いじょです。

_ 参考文献

Wrong timezone with Eloquent Model timestamps on $model->get(), but correct with print_r()
https://stackoverflow.com/questions/63549021/wrong-timezone-with-eloquent-model-timestamps-on-model-get-but-correct-with

Category: [Linux] - 10:44:05



 
Last-modified: 2022-05-14 (土) 10:44:05 (710d)