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 →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article