In this blog, we will learn about UUIDs (Universally Unique Identifiers) and how to use them in a Laravel application. We will also go over an example of how to generate and use UUIDs in a Laravel project.
UUIDs, also known as Universally Unique Identifiers, are strings that are used to identify resources in a unique and consistent manner. UUIDs are usually made up of 32 hexadecimal digits, displayed in five groups separated by hyphens, for a total of 36 characters (e.g. 123e4567-e89b-12d3-a456-426655440000).
One of the main benefits of using UUIDs is that they are globally unique. This means that it is highly unlikely that two different resources will have the same UUID. This makes UUIDs an ideal choice for use as primary keys in databases, as they can be used to uniquely identify a record without the need for a separate, incrementing id field.
Laravel has built-in support for UUIDs, making it easy to use them in your projects. In this section, we will go over an example of how to generate and use UUIDs in a Laravel application.
First, let's create a new Laravel project using the following command:
Next, we will create a new model and migration for a Users table using the following command:
This will create a new User model and a migration for the users table in the database/migrations directory.
Open the migration file and update the up method to include a uuid field as the primary key for the table. It should look something like this:
Next, we need to update the User model to use the UUID field as the primary key. Open the User model and add the following line:
Now, let's run the migration to create the users table in the database:
Now that we have set up our model and migration to use UUIDs, let's look at how to generate UUIDs in Laravel.
One way to generate UUIDs in Laravel is to use the Str::uuid method from the Illuminate\Support\Str class. This method generates a new UUID and returns it as a string.
Here is an example of how to generate a UUID and save it to the users table:
This will generate a new UUID and assign it to the id field of the $user object. The $user object will then be saved to the users table with the generated UUID as the primary key.
You can also use the Uuid facade to generate UUIDs in Laravel. To use the Uuid facade, you will need to add the following line to the top of your file:
Then, you can use the generate method of the Uuid facade to generate a new UUID:
This will generate a new UUID and return it as a string. You can then use this UUID in your application as needed.