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

定制Laravel中的型號日期格式

Karen Carpenter
Karen Carpenter原創
2025-03-07 01:13:09673瀏覽

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