Home >Backend Development >PHP Tutorial >Customizing Model Date Formats in Laravel

Customizing Model Date Formats in Laravel

Karen Carpenter
Karen CarpenterOriginal
2025-03-07 01:13:09682browse

Customizing Model Date Formats in Laravel

Laravel provides multiple ways to control the format of dates when the model is serialized into an array or JSON. From global formatting to customization of specific properties, you can ensure consistency in date display throughout the application.

The following is an example of setting the global date format in the base class:

<?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');
    }
}

Let's look at a practical example of managing different date formats in the booking system:

<?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
            )
        ]);
    }
}

This example shows how to format a date for a specific property using the $casts property, and how to create a custom accessor using the Attribute class to generate a formatted date and duration. The toArray() method demonstrates how to add these custom properties to the model's array representation.

Laravel's date serialization feature ensures consistency in date formats throughout the application while providing flexibility for specific use cases.

The above is the detailed content of Customizing Model Date Formats in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to Use PHP in HTMLNext article:How to Use PHP in HTML