Store who created and last updated a record in Laravel 4

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.AAEAAQAAAAAAAAblAAAAJGRmY2NjYjVhLTk2MDctNGMxYi1hYmYyLWM0MTkxNjRjYWQ5OQ

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.

<?php

Forum::creating(function($forum)
{
    $forum->created_by = Auth::user()->id;
    $forum->updated_by = Auth::user()->id;
});

Forum::updating(function($forum)
{
    $forum->updated_by = Auth::user()->id;
});

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:

<?php

class Forum extends Eloquent {

    //...

    public static function boot()
    {
        parent::boot();

        static::creating(function($forum)
        {
            $forum->created_by = Auth::user()->id;
            $forum->updated_by = Auth::user()->id;
        });

        static::updating(function($forum)
        {
            $forum->updated_by = Auth::user()->id;
        });
    }
}

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.