Customize Laravel Timestamps

1
5548
Customize Laravel Timestamps

Usually, Laravel Eloquent models believe that your table has timestamp fields like created_at and updated_at. What if you want to change the default date format from Y-m-d H:i:s to something else? Or what if you want to disable timestamps for a specific model? Laravel provides lots of customizations to do that. Let’s have a look.

I’m using laravel 8 here. All models are stored in App > Models directory. So take care of it.

# Custom Column Names

Laravel comes with default created_at and updated_at column. Suppose you have a different database and what if you want to change the column name other than the default value? You can define column names into models. You have to define constant CREATED_AT or UPDATED_AT to change values respectively.

/* App > Models > User.php */

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    const CREATED_AT = 'created';
    const UPDATED_AT = 'updated';
}

# Change Datetime Format

Usually, timestamps are organized as Y-m-d H:i:s. To change timestamp format, set the $dateFormat property on your model. You can format anything you want.

/* App > Models > User.php */

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

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

# Using touch() Method

To update updated_at column without changing any fields you can use touch() method directly.

/* App > Http > Controllers > User.php */

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function update(User $user){
        $user->touch();
    }
}

# Using carbon In Timestamps

You don’t need to create carbon instance in created_at and updated_at fields to use carbon functionalities.

/* App > Http > Controllers > User.php */

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function update(User $user){

        //Instead Of
        $createdAt = Carbon::parse($user->created_at);
        $addDays = $createdAt->addDays(3);

        //You can Use
        $addDays = $user->created_at->addDays(3);

    }
}

If you want to cast another column other than the default you can do it in your models too.

/* App > Models > User.php */
    
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{   
    protected $dates = [
        'seen_at',
    ];
}

Learn more about Laravel Framework

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here