Sling Academy
Home/PHP/Laravel Eloquent: Change format of created_at and updated_at columns

Laravel Eloquent: Change format of created_at and updated_at columns

Last updated: January 17, 2024

Overview

Laravel is widely recognized for its elegant handling of database operations, largely attributed to its built-in ORM, Eloquent. A common requirement in web development is to format or mutate the date columns such as created_at and updated_at when working with Eloquent models. This tutorial will guide you through the various methods of changing the date format for these timestamps in a Laravel application.

Understanding Laravel Timestamps

By default, Laravel uses the Illuminate\Support\Carbon class, which extends PHP’s DateTime class, to handle date and time. When timestamps are enabled, Eloquent populates the created_at and updated_at columns with the current date and time in the ‘Y-m-d H:i:s’ format.

Let’s start with the basics and then proceed to more advanced customizations.

Basic Formatting using Accessors

An easy way to customize the format is by using an accessor in your Eloquent model. Accessors allow you to format Eloquent attribute values when you access them.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

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

    protected function getUpdatedAtAttribute($value)
    {
        return \Carbon\Carbon::parse($value)->format('d-m-Y H:i:s');
    }
}

With the code above, anytime you access $post->created_at or $post->updated_at on a Post instance, you’ll receive the date in ‘d-m-Y H:i:s’ format.

Global Customization Using $casts

Another method is by defining your own date format globally for the model using $casts.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $casts = [
        'created_at' => 'datetime:d-m-Y H:i:s',
        'updated_at' => 'datetime:d-m-Y H:i:s',
    ];
}

This will automatically apply the specified date format when the created_at or updated_at attributes are cast to date or datetime data types.

Custom Serialization Using Date Serializers

If you want to customize the serialization of dates globally, you can override the serializeDate method in your model. This method determines how date attributes are serialized when turning an Eloquent model into an array or JSON.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

use DateTimeInterface;

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

Now, whenever a Post model is converted to JSON or an array, the created_at and updated_at attributes will be formatted according to the specified format.

Modifying the Default Timestamp Format

If you need to change the default timestamp format, you can set the $dateFormat property in your Eloquent model to the desired format. This affects how date attributes are stored in the database as well as how they are retrieved.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $dateFormat = 'd-m-Y H:i:s';
}

Be cautious when changing the $dateFormat, as this could impact how dates are stored and parsed by the database.

Conclusion

In this tutorial, you’ve learned multiple ways to format the created_at and updated_at timestamps in Laravel using Eloquent. Each method has its purpose whether it is for an accessor, global serialization, or direct modification. Choose the one that best fits your application’s requirements.

Next Article: Eloquent error: Cannot add a NOT NULL column with default value NULL

Previous Article: Laravel Eloquent: Change column type with migration

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array