Member-only story

Mastering Date Formatting in Laravel Models

I Nyoman Jyotisa
2 min readJan 16, 2025

--

Laravel offers powerful tools to control how dates are formatted when models are serialized to arrays or JSON. Whether you need consistent global formatting or attribute-specific customization, Laravel’s date-handling capabilities allow you to customize and refine how dates are displayed throughout your application.

Here’s a foundational example that demonstrates global date serialization in a base model:

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

Practical Example: Date Formatting in a Booking System

Consider a booking system where various date formats are required for specific attributes:

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)
{…

--

--

No responses yet