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

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
The Laracon Archive image

The Laracon Archive

Read article
Group Adjacent Collection Items in Laravel with chunkBy() image

Group Adjacent Collection Items in Laravel with chunkBy()

Read article
Laravel queue:work Now Prints Why the Worker Stopped image

Laravel queue:work Now Prints Why the Worker Stopped

Read article
Sidecar Brings Statamic's Control Panel to Your Existing Markdown Sites image

Sidecar Brings Statamic's Control Panel to Your Existing Markdown Sites

Read article
Collections chunkBy() and Storage Path Hardening in Laravel 13.30 image

Collections chunkBy() and Storage Path Hardening in Laravel 13.30

Read article
Forte: Parse and Rewrite Laravel Blade Templates image

Forte: Parse and Rewrite Laravel Blade Templates

Read article