Laravel 8 Tutorial: How to Use UUIDs in Your Application

When developing small applications, “standard” incremental IDs are frequently used due to their user-friendliness, storage efficiency, and compatibility with most Frameworks, particularly by junior developers.
Using UUIDs instead of standard incremental IDs in your Laravel 8 application can enhance security. Since standard IDs are predictable, they can be more susceptible to malicious attacks. UUIDs, on the other hand, are unique 36-character strings that are randomly generated, making them much harder to predict and more secure.
Ex: 123e4567-e89b-12d3-a456–426614174000
Using UUID’s in a Laravel 8 application
UUIDs in Laravel are pretty simple to setup: we will need to follow 3 steps:
Creating a UUID column in the migration file.
Generating a unique UUID on model creation.
Telling Laravel our model doesn’t use incremental ID.
Creating a UUID’s column
To define our id column, Laravel comes with an awesome uuid method, provided by the Illuminate\Database\Schema\Blueprint class.
And also, it is important to define our UUID column as the primary key if we want to use it as the entity’s identifier.
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->text('content')->nullable(false);
$table->uuid('user_id')->nullable(false);
$table->timestamps();
$table->foreign('user_id')
->on('users')
->references('id')
->onDelete('cascade');
});
}Generating a unique UUID on model creation
In order to generate a UUID when creating a model, we will use the bootedmethod in which we will use the creating event, as follow:
protected static function booted(): void
{
static::creating(function (Post $post) {
$post->id = Str::uuid()->toString();
});
}We are using the uuid method available in the Str Facade. This method returns an object of type Ramsey\Uuid\UuidInterface. We will finally need to get a string representation of this UUID object before assigning it to our model, by using the toString() method.
Note that it also is possible to explicitly cast the returned Ramsey\Uuid\UuidInterface object, rather than using its toString()method: $user->id = (int)Str::uuid(); .
Last but not least, it is important to inform Laravel that the ID used for this model is not incremental. By default, Laravel is configured to use numeric IDs that will be cast to an integer. Here, we will use the $incrementing property inherited from the extended Model Class, to tell Laravel not to cast our id.
public $incrementing = false;Congratulations! You’ve successfully configured your Laravel application to use UUIDs. By switching to UUIDs, you’ve increased the security of your application and made it more robust. I hope you found this article informative and helpful. If you have any suggestions or questions, please leave a comment below. Thank you for reading!