Laravel provides a very handy way to store who created and last updated a given row in the database. Actually there are two very similar ways you can implement this.

The basic idea is that model events allow you to perform actions when a model object is created, updated, deleted and so on. We will use these events to perform the saving of the user who created or updated the given row.

1. Model events in the global scope

Using model events you can specifiy code blocks that will run in case of different events that a model object fires.

You can specify these model events for example in the same php file where your model resides, but outside of the class definition.

2. Model events inside the boot function of a model

The second option is similar in effect to the first one. It works by overriding the boot function of the model and through static methods provide the functions the will run when the model object is created or updated. Here is an example of that:

You can see that when a model object is created we update both the created_by and updated_by columns, because in this case the updating event won’t fire. In case of an update to an existing record, the updating event will fire so we are specifying the code for setting the updated_by colum value there. This example assumes that you are using Laravel’s authentication metod, because we are using that to get the user who is currently logged in, and then it’s id.