Setting only the created_at timestamp in Laravel

In Laravel 5 migrations, the method $table->timestamps() creates the  created_at and  updated_at columns, but sometimes we just need one of the two. The issue is that Eloquent models by default use both and disabling one of the two can be tricky and counterintuitive. In this article, I will show you how to set only one of the fields in a safe, reusable and decoupled way using Model Observers. This approach will work for any number of models in your application.

In following tutorial we will eliminate the updated_at attribute of the OrderLog Model.

1) Create the created_at field on the migration

Please note that we are not using the timestamps() to generate both.

2) Create an Observer

In App\Observers\ folder, create the SetCreatedAt with the following code:

Optional: If you wanted to use a custom column name, you can! Note that we are using the internal setter that is defined in the Model class. This allows you to set any custom name with the CREATED_AT constant in the model. How to use custom timestamp column names

3) Register the observer in the boot method of the AppServiceProvider

Remember to replace  OrderLog with your model. Here you may add more lines for each one the models.

4) Disable the default timestamps in the model.

In the model, we need to tell Laravel not to try to save both timestamps. Just add this line to the model.

Congratulations! That’s all you need to get this to work. A reusable piece of code that is decoupled from the models and that closely resembles the vanilla code.

Extra: What is a Model Observer?

When a model is modified, Laravel automatically fires different events that can be listened for. An observer is a class that defines a listener (method) for any or all of those events. Then when those events fire, the appropriate method in the observer will be executed. The methods receive the model as the first argument so that you can do stuff like modify it, send a notification, update some other model, etc. The observers need to be registered in the AppServiceProvider. That’s how Laravel knows where to ‘send’ the events when they trigger.

In our example, we listen for the creating state/event that fires just before the creation, and then we set the created_at attribute.

Other useful events are:

  • creating: before creation
  • created: after creation
  • updating: before update
  • updated: after update
  • saving: before creation or update
  • saved: after creation or update
  • deleting: before deletion
  • deleted: after deletion
  • restoring: before restoration
  • restored: after restoration

Troubleshooting

This error means that the updated_at column doesn’t exist. If you want it, then use the $table->timestamps() in the migration to create both, but if you only want the cration date, then follow this tutorial.

Share Post :