8 Tricks with Laravel Timestamps

8 Tricks with Laravel Timestamps

By default, Laravel Eloquent models assume your table has timestamp fields — created_at and updated_at. But there’s plenty of things you can do to customize them or perform some interesting operations. Let’s take a look.

1.Disable Timestamps

If your DB table doesn’t have those fields, and you will try to do something like Model::create($arrayOfValues); — you will get SQL error. Laravel would try to automatically fill in created_at/updated_at and wouldn’t find them.

To disable that automatic timestamps, in your Eloquent Model you need to add one property:

class Role extends Model
{
public $timestamps = FALSE;

// … other model properties and methods
}

2. Change Timestamp Column Names

What if you’re working with non-Laravel database and your timestamp columns are named differently? Maybe, you have create_time and update_time. Luckily, you can specify them in the model, too:

class Role extends Model
{
const CREATED_AT = ‘create_time’;
const UPDATED_AT = ‘update_time’;

3. Change Timestamp Date/Time Format

Here, I will just quote official Laravel documentation:

Before Laravel 7, dates would be serialized to a format like the following: 2019–12–02 20:01:00. From Laravel 7, dates serialized using the new format will appear like: 2019–12–02T20:01:00.283041Z. If you need to customize the timestamp format, set the $dateFormat property on your model.