UUID Generation in Eloquent Models in Laravel
Integrate UUIDs into Laravel Models for Unique and Reliable Identifiers using Trait approach
UUIDs (Universally Unique Identifiers) are a fantastic way to give your database records unique keys. Unlike auto-incrementing IDs, UUIDs are almost guaranteed to be unique, even across different databases and instances. This makes them perfect for distributed systems or when you need to merge databases.
They can also be really useful in APIs, where they can serve as unique resource identifiers. As well as in Dashboards or Back end interfaces where we could use them as route parameters instead of plain old IDs.
In this article, we’ll describe how to implement UUID generation for Eloquent models in Laravel using a reusable trait.
Step 1: Add UUID column in table in database
First, you need to add a UUID column to your table in the database (if your table is already has uuid column, skip this step). You can do this by creating a new migration or modifying an existing one. Here's an example of Laravel migration how to add a UUID column to a table:
public function up()
{
Schema::table('example_table', function (Blueprint $table) {
$table->uuid('uuid')->unique()->nullable();
});
}
public function down()
{
Schema::table('example_table', function (Blueprint $table) {
$table->dropColumn('uuid');
});
}
Step 2: Create the Trait
Let’s create a trait that automatically generates and assigns a UUID when a new Eloquent model is created.
<?php
declare(strict_types=1);
namespace Labrodev\Uuidable;
use Illuminate\Support\Str;
trait ModelHasUuid
{
/**
* Boot the trait and add the creating event listener.
*
* @return void
*/
public static function bootModelHasUuid(): void
{
static::creating(function ($model) {
/** @var static|self $model */
if (empty($model->{$model->fetchUuidColumn()})) {
$model->{$model->fetchUuidColumn()} = Str::uuid();
}
});
}
/**
* Get the name of the UUID column.
*
* @return string
*/
protected function fetchUuidColumn(): string
{
return 'uuid';
}
}
This trait hooks into the creating
event of the model and assigns a UUID if the UUID column is empty. The fetchUuidColumn
method specifies the column name used for storing the UUID. If your column is named differently, you can override this method in your model.
When we use the bootModelHasUuid
static function, it seamlessly integrates with Laravel Eloquent's booting mechanism. Laravel automatically calls the boot
method on all traits used by a model, allowing the bootModelHasUuid
method to contribute its functionality to the model's primary boot method. This ensures that the UUID assignment logic is consistently applied whenever a new model instance is created.
Step 3: Using the Trait in a Model
To use the ModelHasUuid
trait, include it in your Eloquent model like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Labrodev\Uuidable\ModelHasUuid;
class ExampleModel extends Model
{
use ModelHasUuid;
}
Step 4: Customizing the UUID Column Name
If your UUID column is named something other than uuid
, you can override the fetchUuidColumn
method in your model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Labrodev\Uuidable\ModelHasUuid;
class ExampleModel extends Model
{
use ModelHasUuid;
/**
* Override method to specify a custom column name.
*
* @return string
*/
protected function fetchUuidColumn(): string
{
return 'custom_uuid_column';
}
}
Conclusion
By following these steps, you can implement UUID generation for Eloquent models in Laravel, providing a reliable and unique identifier for your records. This approach is encapsulated in a reusable trait, making it easy to apply to any model within your application. For the full implementation, check out our laravel-uuidable package on GitHub.
Thanks for reading!
Subscribe to our Substack to get more tips and tutorials on Laravel development and best practices delivered straight to your inbox.
Preview photo credit: