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.
