How to Format Date Time in Eloquent (Laravel)

Updated: January 17, 2024 By: Guest Contributor Post a comment

Introduction

When working with Eloquent in Laravel, the handling of date and time fields is an essential aspect of development. Eloquent, which is the ORM (Object-Relational Mapper) included with Laravel, makes working with dates seamless by providing features that adhere to the ‘convention over configuration’ paradigm. In this tutorial, we’ll explore different ways to format date-time fields utilizing Eloquent in Laravel.

Understanding Carbon

In Laravel, date and time fields are automatically cast to Carbon instances, which is a PHP date-time library that extends the native DateTime class. This means that by default, you can manipulate these fields with a variety of convenient methods that Carbon provides.

Code example:

$user = User::find(1);
echo $user->created_at->format('Y-m-d H:i:s');

In the above example, created_at is a typical timestamp field in any Eloquent model which by default is a Carbon instance, and we’re calling the format() method on it to represent the timestamp in a specific pattern.

Customizing Date Formats

In some scenarios, we might want to customize the format of our date fields, or perhaps we have a special date field that doesn’t adhere to the default casting provided by Eloquent. Here’s how we can achieve that.

Using Accessors

Laravel’s accessor allows you to perform operations on an attribute after it’s retrieved from the database but before it’s returned to the user. You can define an accessor for a date attribute to change its format.

Code example:

class User extends Model
{
    protected function getCreatedAtAttribute($value)
    {
        return Carbon::parse($value)->format('d/m/Y H:i:s');
    }
}

This accessor will format the created_at attribute whenever it’s accessed through the model instance. Every time you call $user->created_at, you’ll now receive the date in ‘d/m/Y H:i:s’ format.

Using Mutators

Sometimes we also need to format the dates when saving to the database. For this, you can define a mutator that will be used when setting the value of a model attribute:

Code example:

class User extends Model
{
    protected function setCustomDateAttribute($value)
    {
        $this->attributes['custom_date'] = Carbon::createFromFormat('d/m/Y', $value)->toDateTimeString();
    }
}

This mutator takes a date in ‘d/m/Y’ format and converts it into a format acceptable by the database before saving it to the custom_date attribute.

Global Date Serialization Format

The default date serialization format can be changed in your model by overriding the serializeDate method from the parent model class. This will affect the JSON representation of your date times.

Code example:

class User extends Model
{
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('d/m/Y H:i:s');
    }
}

This will format all dates within the User model when serializing into an array or JSON.

Localization of Dates

Localization can be extremely helpful if you cater to a multi-region audience. Laravel makes it easy to localize your model’s date and time representations.

Code example:

$user = User::find(1);
echo $user->created_at->translatedFormat('l jS F Y');

This will output the localized date format for the created_at attribute using Carbon’s translatedFormat() method.

Date Scopes and Querying

Adding custom scopes can streamline the process of querying records by their date fields.

Code example:

class User extends Model
{
    public function scopeCreatedAtDay($query, $day)
    {
        return $query->whereDate('created_at', $day);
    }
}

// Usage within a controller
User::createdAtDay('2023-04-05')->get();

This scope filters users created on a particular day.

Carbon’s Additional Methods

Besides format(), Carbon offers various other methods to help with date time formatting and manipulation. Here are a few of them:

  • diffForHumans() – provides a human-readable difference between the given date and now.
  • today(), yesterday(), tomorrow() – return instances representing respective dates.
  • startOfDay(), endOfDay() – modify the time to 00:00:00 or 23:59:59 respectively.

Conclusion

Mastering the handling of date and time fields in Eloquent unlocks TypeScript’s powerful suite of features, enabling clean, readable, and maintainable code. Through this tutorial, you should now feel comfortable working with various date and time operations within your Laravel models. Happy coding!