Using UUID in Laravel
UUID is a 128-bit number that identifies information in a computer system. UUID can be used for primary key of database tables.
What is UUID?
A Universal Unique Identifier (UUID) is a 128-bit number that identifies information in a computer system.
“Wikipedia”
Simply, UUID is a randomly generated set of character that result a unique identifier. UUID example :
323e4r57-f87b-43d7-c123-441166474400
Why UUID?
Usually we use id with Auto Incrementing as Primary Key of tables in our database. Then in our app URLs are like this :
http://myapp.com/user/11
http://myapp.com/user?id=11
With the URL, one can recognize the URL easily and guess URL for the data he wants. UUID is one of solution to solve that problem.
Use UUID in Laravel
To use UUID in Laravel we have to use package from Ramsey UUID. Open your app in terminal then run command below to install Ramset UUID package :
composer require ramsey/uuid
After installing the package, now we can use UUID in our app. Usage example :
use Ramsey\Uuid\Uuid;
$uuid = Uuid::uuid4();
printf(
"UUID: %s\nVersion: %d\n",
$uuid->toString(),
$uuid->getFields()->getVersion()
);
Updating Migration File
I want to use UUID on User model so I will make changes to User’s migration class. In your migration file, change this :
$table->id();
to this :
$table->uuid('id')->primary();
Then you can run :
php artisan migrate
or if you have done before, you can run :
php artisan migrate:fresh
Note: command above will delete all tables and run all migrations from start, it will clear all previous data on database.
or alternatively you can create new migration file to alter your table column.
Create a Traits and use it on Model
Usually we create database record in the following way :
User::create($data);
But the problem is primary key of User is no more an integer, so it can’t auto incrementing. So we will modify our model (User) in some part :
Then we can create a record of database as usual. What if we want to use UUID in other models? you can just copy and paste part of modification above or you can use a Traits like the example below :
Then you just need use the Traits on model that you want to use UUID. For example :
So UUID can be useful if you won’t expose the id of your record, but UUIDs aren’t easy to sort and remember.
Thanks for read my post, if you have any question or want to discuss please feel free to leave a comment. See ya.