Laravel 4 Model Events: Dynamicaly populate columns on insert/update

When I create some sort of admin panel, I usually want to know not only when a user created or edited an item (post), but also who that user was.

Considering this, I always add two additional columns to my tables: created_by and updated_by. This, along with the timestamps from Laravel, is the best way to keep track of latest changes of a database record.

In the past, when I needed to create/update a post I would use:

As you can see, when I created a post I added the line $post->created_by = Auth::id();. The same happens when I update a post: $post->updated_by = Auth::id();.

All goes well, but what if there was a better way to do this, just like the timestamps that Laravel inserts on every insert/update.

And it seems that there is a better way. By using the Laravel’s Model events, you can easily add values to a column on insert or update:

“Eloquent models fire several events, allowing you to hook into various points in the model’s lifecycle using the following methods: creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored.”

OK. We can modify the model so that on creating or updating a record, we can populate certain columns.

Considering we have a Post model, we can insert a boot method where we register our event bindings. That means that inside the Post class we can call that same class and attach the events to it. Let’s try it:

Now, whenever I create/update a post, it automatically inserts/updates the user’s id in the table.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

No spam? * Time limit is exhausted. Please reload CAPTCHA.