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:

$post = new Post; // that means that we have a Post model...
$post->title = $title; // $title is taken from the form...
// other fields that must be saved
$post->created_by = Auth::id(); // considering that you use the Laravel Authentication, you get the user id
$post->save();

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:

<?php

class Post extends Eloquent {

  public static function boot()
  {
    parent::boot();
    // first we tell the model what to do on a creating event
    static::creating(function($post)
    {
      $post->created_by = Auth::id();
    });
    // // then we tell the model what to do on an updating event
    static::updating(function($post)
    {
      $post->updated_by = Auth::id();
    });
  }
}

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

$post = new Post; // that means that we have a Post model...
$post->title = $title; // $title is taken from the form...
// other fields that must be saved
//no more need for $post->created_by = Auth::id(); because the model will fill that field dynamically
$post->save();

Leave a Reply

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

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