Last Updated: February 25, 2016
·
11.7K
· stevebauman

Change created_at display format globally in Laravel 4

Say we have a typical Eloquent model like this:

<?php

class Example extends Eloquent {
    protected $table = 'example';
}

What we need to do is create a base model that all models will extend from, allowing us to change the date format that is displayed from the 'created_at' column that is default in laravel.

Create a base model named 'BaseModel.php' in your 'models' directory, and paste the following:

<?php
use Carbon\Carbon;

class BaseModel extends Eloquent {

    public function getCreatedAtAttribute($attr) {        
        return Carbon::parse($attr)->format('d/m/Y - h:ia'); //Change the format to whichever you desire
    }
}

Now from the eloquent model show above, change 'Eloquent' to 'BaseModel' like this:

<?php

class Example extends BaseModel {
    protected $table = 'example';
}

Now all your created_at timestamps can be formatted globally throughout your application by simply extending your model to the BaseModel.

2 Responses
Add your response

Thanks ...Its working well

over 1 year ago ·

Very good idea, and so simple! Bravo.

over 1 year ago ·