Skip to main content

Using a trait to add UUID to a Laravel 5 Model

The past weeks i’m spending my free time with building a application using Laravel 5.4, but I wanted to use an UUID on a few models. So I did what I always do, go look on packagist to find if somebody already done that work for me. And they did, but what I found was either over engineered and / or implementing their own logic of creating and validating the UUID.

But I know that Laravel comes with the UUID package of Ben Ramsey so that kind of bugged me a lot. Why duplicate logic when there is a battle tested library reachable within the /vendor folder?

This was a good opportunity to dive in the world of Laravel models,and especially the events ( ) that models fire off. Sure I could’ve done the same per model, but somewhere I read that the proper way of doing this was using a trait and a event.

The model, the code and the trait.

Firstly I added a UUID to my table with a migration and added the UUID as fillable to my model. Not sure if that actually needs to be fillable. But it got the job done ;)  

The UP of the migration

    public function up()
  Schema::create(‘images’, function (Blueprint $table) {

The model with UUID

    namespace App\Models;
use \App\Traits\Uuids;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
  use Uuids;

  protected $fillable = [

Now I could have added the code of the trait to this post, but I thought it was more usable as a GIST on github.

There are two methods in the trait, first there is the static::creating in the boot method, add a static method that is executed just before the model get’s persisted to the database. And within that method I use create a new UUID4 and set the value to the uuid field on the model. For convenience I’ve added a config variable to the app namespace that allows me to globally change the UUID column in the model. 

Then there is the ScopeUuid() method that allows me to receive the model from the database simple by calling  Image::Uuid(‘a8c33a08-04b0-4af3-a972-60d3587a7f4a’); and retrieve on Model class back. This method validates if the passed UUID is actually a valid on.

That’s it, one simple trait and I had all the UUID handling I needed for now.

(disclaimer, if I made mistakes or wrong assumptions, find me on twitter and tell me. I’m new to Laravel and still learning about the ins and outs of the framework)