首頁 > 後端開發 > php教程 > 定制Laravel中的型號日期格式

定制Laravel中的型號日期格式

Karen Carpenter
發布: 2025-03-07 01:13:09
原創
668 人瀏覽過

Customizing Model Date Formats in Laravel

Laravel 提供多種方法來控制模型序列化為數組或 JSON 時日期的格式。從全局格式到特定屬性的自定義,您可以確保整個應用程序中日期顯示的一致性。

以下是一個在基類中設置全局日期格式的示例:

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DateTimeInterface;

class BaseModel extends Model
{
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
}
登入後複製

讓我們來看一個在預訂系統中管理不同日期格式的實際示例:

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
use DateTimeInterface;

class Booking extends Model
{
    protected $casts = [
        'check_in' => 'datetime:Y-m-d',
        'check_out' => 'datetime:Y-m-d',
        'created_at' => 'datetime:Y-m-d H:i:s',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    protected function checkInFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->check_in->format('l, F j, Y')
        );
    }

    protected function duration(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->check_in->diffInDays($this->check_out)
        );
    }

    public function toArray()
    {
        return array_merge(parent::toArray(), [
            'check_in_formatted' => $this->checkInFormatted,
            'duration_nights' => $this->duration,
            'human_readable' => sprintf(
                '%s for %d nights',
                $this->check_in->format('M j'),
                $this->duration
            )
        ]);
    }
}
登入後複製

此示例展示瞭如何使用 $casts 屬性設置特定屬性的日期格式,以及如何使用 Attribute 類創建自定義訪問器來生成格式化的日期和持續時間。 toArray() 方法則演示瞭如何將這些自定義屬性添加到模型的數組表示中。

Laravel 的日期序列化功能確保了整個應用程序中日期格式的一致性,同時為特定用例提供了靈活性。

以上是定制Laravel中的型號日期格式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板