Home » Laravel » How to Generate UUID in Laravel

How to Generate UUID in Laravel

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:

app/Console/Commands/PrintUuidCommand.phpuse Ramsey\Uuid\Uuid;

app/Console/Commands/PrintUuidCommand.php$uuid = Uuid::uuid4()->toString(); dump($uuid);

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:

app/Console/Commands/PrintUuidCommand.phpuse Illuminate\Support\Str;

app/Console/Commands/PrintUuidCommand.php$uuid = Str::uuid(); dump($uuid);

Also Laravel has the faker() helper that was developed for testing purposes, and it can create UUIDs too:

app/Console/Commands/PrintUuidCommand.phpuse Faker\Factory;

app/Console/Commands/PrintUuidCommand.php$faker = Factory::create(); $uuid = $faker->uuid; dump($uuid); dump(fake()->uuid);

That’s it.

Leave a Comment

Exit mobile version