UUID, or universally unique identifier, can be used when you need to have some unique string, for example, for HTML element identifiers, any tracking identifiers, or as a primary key for Eloquent models.
It is better to use UUID as an identifier publicly because it is more secure than incrementing identifiers. In this short article, we will explain how to generate a UUID in Laravel in different ways.
How to Generate UUID in Laravel
There are several methods to generate UUIDs, and, of course, you should not do it manually. But all of them use the ramsey/uuid package. So, you can use this class directly:
$uuid = Uuid::uuid4()->toString();
You will get a valid UUID as a string:
Let’s have a look at other ways to generate UUIDs. The Illuminate\Support\Str facade has a static method uuid() that can generate a UUID for you:
$uuid = Str::uuid();
Also Laravel has the faker() helper that was developed for testing purposes, and it can create UUIDs too:
$faker = Factory::create();
$uuid = $faker->uuid;