Hi guys, today I’m going to share with you some timestamp tricks in Laravel. Let’s dive in:

1- Disable Timestamps

If your DB table doesn’t contain timestamp fields created_at and updated_at, you can specify that Eloquent model wouldn’t use them, with $timestamps = false property.


2- Change Timestamp Column Name

If you want to use different names of the columns used for timestamps, you need to set the CREATED_AT and UPDATED_AT constants in your model.


3- Change Date/Time Format

By default, timestamps are formatted as 'Y-m-d H:i:s'. If you need to customize the timestamp format, set the $dateFormat property on your model. This property determines how date attributes are stored in the database:


4- Order by latest / oldest

You can order data by timestamp using two shortcut methods which are latest() & oldest() , example :

You can also specify witch column to order by, example :

5- Update Without touching updated_at Column

Normally, the update eloquent method automatically updates current timestamps. We can easily stop updating timestamps during updating data like this:

6- Set new value to ONLY updated_at column

This trick is the opposite of previous trick. We can set new value to only updated_at column.

Whereas in some cases, you would like to update parent record along with current eloquent model as well.

For example if some details was updated then you want to consider that post record should have new updated_at as well.

For that, you need to define parent touches in eloquent model:

7- Timestamp Fields are Carbon Automatically

created_at and updated_at are casts as $dates of Eloquent model by default. So, the user can perform carbon operation in them without converting in carbon instance.

Read Also  Handling Multiple File Upload In Laravel

8- Timestamp In Pivot Table With Many-to-Many Relationships

By default, the pivot tables does not contain timestamp. But if you do want to save the timestamps automatically, you need to add them into migration file. Then define relationship using ->withTimestamps();

That’s it. Thanks for reading.

    No Comments

    Leave a Reply

    your email address will not be published. required fields are marked *