Customizing Model Date Formats in Laravel

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.

Customizing Model Date Formats in Laravel

ARE YOU TIRED OF LOW SALES TODAY?

Connect to more customers on doacWeb

Post your business here..... from NGN1,000

WhatsApp: 09031633831

ARE YOU TIRED OF LOW SALES TODAY?

Connect to more customers on doacWeb

Post your business here..... from NGN1,000

WhatsApp: 09031633831

ARE YOU TIRED OF LOW SALES TODAY?

Connect to more customers on doacWeb

Post your business here..... from NGN1,000

WhatsApp: 09031633831

Customizing Model Date Formats in Laravel

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.

format('Y-m-d H:i:s');
    }
}

Let's explore a practical example of managing different date formats in a booking system:

 '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.


The post Customizing Model Date Formats in Laravel appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow