Home » Laravel » How to Generate UUID in Laravel

How to Generate UUID in Laravel

UUID or Universally unique identifier can be used where you need to have some unique string, for example for HTML element identifiers, any tracking identifiers or as a primary key for Eloquent models. By default, Eloquent uses an integer as the primary key, but if this key is visible to visitors, it is better to make it not incremental. UUID is a great solution for this issue.

In this short article we will explain how to generate UUID in Laravel, and how to use UUID as a primary key for Eloquent models.

How to Generate UUID in Laravel

There are several methods to generate UUID, and, of course, you should not do it manually. But all of them use ramsey/uuid package. So, you can use it directly:

use Ramsey\Uuid\Uuid; //... $uuid = Uuid::uuid4()->toString();

You will get a valid UUID as a string:

Let’s have a look at other ways to generate UUID. The Illuminate\Support\Str facade has a static method uuid() that can generate UUID for you:

use Illuminate\Support\Str; $uuid = Str::uuid()

Also Laravel has a faker class that was developed for testing purposes, and it can create UUID too:

use Faker\Factory; $faker = Factory::create(); $uuid = $faker->uuid;

Or:

$uuid = faker()->uuid;

How to Use UUID for Models in Laravel

Now, you know how to make UUID, let’s dive into how to use it as a primary key in Eloquent models. First, you should change migration for the model. I will use the Article class for this example. The article will have an id, title, and content. The id field must have a UUID type and be the primary key:

Schema::create("articles", function (Blueprint $table) { $table->uuid("id")->primary(); $table->string("title"); $table->text("content"); $table->string("slug"); $table->timestamps(); });

Next, you should change the Article model. Change the $incrementing variable to false, and set the $keyType variable to string:

public $incrementing = false; public $keyType = 'string';

Also you should set the value for the id variable before the model will be saved into the database. The model has a static creating() method that allows registering callback function which will be called before saving. You can use it:

public static function boot() { parent::boot(); self::creating(function (Model $model) { $model->setAttribute($model->getKeyName(), Str::uuid()); }); }

Now, you can try to create a few articles using factory and ensure that they use UUID as the primary key:

Also, you can do it at the database level. If you use PostgreSQL 13 or higher, you can use the gen_random_uuid() method to generate UUID automatically as a default field value:

$table ->uuid("id") ->primary() ->default(\Illuminate\Support\Facades\DB::raw("gen_random_uuid())"));

MySQL/MariaDB databases have UUID() method, that can be used for the same purpose:

$table ->uuid("id") ->primary() ->default(\Illuminate\Support\Facades\DB::raw("UUID()"));

Note, that if you want to use foreignId() or morphs() methods in any migration that points to the articles table, you should use their UUID versions: foreignUuid() and uuidMorphs().

Wrapping Up

In this short article we have explained why and how to use UUID in Laravel. As you can see it is pretty easy. Using UUID instead of integers is highly recommended for resources that can be visible to visitors.

Leave a Comment