Welcome to ahex technologies

How to generate Uuid in Laravel

Uuid in Laravel
  • December 20, 2017
  • Sanjay
  • 0

What is Uuid ?

It stands for Universal Unique Identifier. As the name suggests, it is used for uniquely identifying a resource over a network. The usage of it in a project has it own set of pros and cons and is debatable, but we will not focus on that currently and will stick to the topic of this blog. You can use it in your project as per your requirements. The Laravel version we are using in this blog is 5.5.

Installing Package

We are going to use webpatser/laravel-uuid package to generate it. Use composer to install this one:

composer require "webpatser/laravel-uuid:^3.0"

Once composer installs it, you will get a message like this one on your screen:

Discovered Package: webpatser/laravel-uuid

Migrations

In Laravel migrations, there is column definition:

$table->uuid('id');

We can use this definition in our migrations to create column to store it.

Creating the Trait

What is trait ?

A “trait” is like an abstract class which means it cannot be instantiated but it contains methods that can be used by other concrete classes. As per definition on php.net

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of 
single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class 
hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical 
problems associated with multiple inheritance and Mixins.

We are creating a trait so that it becomes less tedious for us to generate the unique identifier with minimum code. So I have created a “traits” folder inside my project. Here is the code for it:

namespace App\Traits;

trait Uuids 
{
    /**
     * 
     */
    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            $model->{$model->uuid} = 
            str_replace('-', '', \Uuid::generate(4)->string);
        });
    }
}

The static method boot will generate the unique identifier and will assign it to the model attribute that will be used for storing the unique identifier. If you will look closely, we are removing the ‘-‘ from the unique identifier. I removed it because it shortens the length of the Uuid somewhat (saving storage space … ha ha). If you want that then just use “\Uuid::generate(4)->string” method.

Creating the model

A Model class in Laravel is used to interact with the underlaying database table. Usually each table has its own model class. Lets create a model class:

php artisan make:model Models/TestModel

I keep my model class in “Models” folder thats why using “Models/TestModel”, you are free to use your directory. Once this model is created, open the file and initialize the column name that will store the generated unique identifier. For example:

namespace App\Models\TestModel;

use Illuminate\Database\Eloquent\Model;
use App\Traits\Uuids;

class TestModel extends Model
{
    
    use Uuids;
    
    /**
     * Table associated with the model class.
     * 
     * @var string
     */
    protected $table = 'table_name';
    
    /**
     * Attributes that cannot be mass assigned.
     * 
     * @var array
     */
    protected $guarded = ['id'];
    
    /**
     * The attribute to be used for storing the uuids.
     *
     * @var string
     */
    public $uuid = 'project_uuid';
    
}

Now whenever an insert is done using the eloquent for this model, the unique identifier for it is generated and initialized automatically.

Happy Coding