iT邦幫忙

0

[Laravel] $casts (Attribute Casting)

前言

前端通常需要顯示時間,但是我們從資料庫撈出來的時間很醜:2020-03-28T21:34:44.000000Z。明明在資料庫看到的是2020-03-28 21:34:44呀~ 花生神模式?
原來是因為 Eloquent 內建的 date 的 Mutator,把時間都轉為 Carbon 的 instance。
官方文件:
Eloquent will convert the createdat and updatedat columns to instances of Carbon, which extends the PHP DateTime class and provides an assortment of helpful methods.

而這個 instance 輸出成 string 格式就會是一般我們看到的 2020-03-28 21:34:44,不過我們從資料庫撈出來依然是 instance,所以醜醜的,因此我們想做一件事,把它轉成 string。 第一個想到的是可以寫一個 Accessor(這是什麼?), 後來發現還有一個東西叫 $casts! 方便許多! 一起來一探究竟吧!

說明

官方文件:
The $casts property on your model provides a convenient method of converting attributes to common data types.

The supported cast types are: integer, real, float, double, decimal:, string, boolean, object, array, collection, date, datetime, and timestamp.

用法

Post Model

我們讓 created_at 和 updated_at 顯示不同的格式

protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'timestamp',
    ];
測試結果

時間結果

P.S.
標註時區的方法:

protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:sP',
    ];

結果為:
2020-03-29 12:27:57+08:00

感謝 Ray 大!!


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
aa4731073
iT邦新手 4 級 ‧ 2022-07-21 10:03:03

請問如果要顯示2020-03-2的格式話

protected $casts = [
        'created_at' => 'datetime:Y-m-d',
    ];

這樣設定對嗎?

我要留言

立即登入留言