Automatically Generating a UUID on your Laravel Models

Jeffrey Kilroy
Nov 20, 2017 · 2 min read
Photo by Patrick Perkins

A UUID (Universally unique identifier) is an ID that can be given to your table rows to identify them in a manner that is a bit nicer than a sequential table id. This works great in cases where you don’t want your users to guess how many records you might have in a table or even worse, give them clues on how to take advantage of your application.

There is already a really great package to handle the generation of UUID’s: https://github.com/webpatser/laravel-uuid

Using this package, it’s a piece of cake to generate a new UUID to add to your model:

$uuid = Uuid::generate();

As it turns out, by adding the following in your model you can make sure every time a new model is created, it will generate and save its own UUID:

public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->uuid = (string) Uuid::generate(4);
});
}

There was still something missing for me in this process though, as I saw myself adding this more and more to my models it was just too much repetition.

What I wanted to do was add a simple Trait to any model that had UUID’s so they would have this generated for them during creation, but how would I use this same boot method? Do I need to create an event observer they all need to call or what?

❤️Enter Magic❤️

This issue changed when I found out about bootable model traits: https://tighten.co/blog/laravel-tip-bootable-model-traits

By creating this simple “HasUUID” trait, and adding a “ bootHasUUID” method, I can drop in this functionality and be done.

Additionally, this trait can house some simple scopes and methods like “findByUUID()”

I ended up making this simple trait available in a package, which will also pull in webpatser/laravel-uuid. So all that is needed to install is:

  • Run “composer require binarycabin/laravel-uuid”
  • Add the trait on your model “use \BinaryCabin\LaravelUUID\Traits\HasUUID;

Take a look at the full package and trait here: https://github.com/binarycabin/laravel-uuid

Binary Cabin

Custom Web Applications

Jeffrey Kilroy

Written by

Web Developer at Binary Cabin

Binary Cabin

Custom Web Applications

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade