首页 > 后端开发 > php教程 > 定制Laravel中的型号日期格式

定制Laravel中的型号日期格式

Karen Carpenter
发布: 2025-03-07 01:13:09
原创
672 人浏览过

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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板