Laravel – Change String Date Format using Accessors

In Laravel if you are storing date in the mysql database and on the frontend you want to change the display format, you can do so easily via Model accessors and mutators.

Accessors, mutators, and attribute casting allow you to transform Eloquent attribute values when you retrieve or set them on model instances. You can read more about Laravel’s mutators and casting in the official documentation.

Let’s say you have a Post model in which you have a column named published_at which stores in the date as a string in the following format Y-m-d. If you are looking to change the display format on the frontend then you can do so by using Carbon library


 protected function publishedAt(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => Carbon::parse($value)->format('l jS \\of F Y h:i:s A'),
        );
    }

Thus when you output the date using $post->published_at, it will give the date in following format.

Livewire Component Library

Monday 30th of May 2022 12:00:00 AM

Host Laravel Application on DigitalOcean

Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.

Site Footer