Laravel Tutorials

Customizing Model Date Formats in Laravel

Published
Customizing Model Date Formats in Laravel image

Laravel provides several approaches to control how dates are formatted when models are serialized to arrays or JSON. From global formats to attribute-specific customization, you can ensure consistent date presentation across your application.

<?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 explore a practical example of managing different date formats in a 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
)
]);
}
}

Laravel's date serialization features ensure consistent date formatting throughout your application while providing flexibility for specific use cases.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Laravel Image Responses: Serve Resized Images From Routes image

Laravel Image Responses: Serve Resized Images From Routes

Read article
Pause All Laravel Queues During a Deploy image

Pause All Laravel Queues During a Deploy

Read article
Laravel Terminal UI for the artisan dev Command image

Laravel Terminal UI for the artisan dev Command

Read article
Pause All Queues and a New artisan dev UI in Laravel 13.25 image

Pause All Queues and a New artisan dev UI in Laravel 13.25

Read article
Laravel monitoring that doesn't bill you by your traffic image

Laravel monitoring that doesn't bill you by your traffic

Read article
Mock PHP Classes in Tests With the Double Library image

Mock PHP Classes in Tests With the Double Library

Read article