Laravel Story: Replace Auto Increment ID with UUID

Krisna Wijaya
2 min readJul 9, 2017

Here is the simple steps that you need to do to replace Auto Increment ID that generated from Laravel Authentication Quickstart.

First, install Ramsey UUID with this following commands.

composer require ramsey/uuid

Seconds, replace increment to uuid on users database migration.

Before:

$table->increments('id');

After:

$table->uuid('id');

Third, add UUID on register user process. Open the RegisterController.php file. Then use Ramsey UUID

use Ramsey\Uuid\Uuid;

After that, add this line on create function

'id' => Uuid::uuid4(),

Last steps is modifying the user model. So open the User.php file and ID to the fillable array

/**
* The attributes that are mass assignable.
*
*
@var array
*/
protected $fillable = [
'id', 'name', 'email', 'password',
];

Add this code to disable the auto increments process.

/*** Indicates if the IDs are auto-incrementing.** @var bool*/public $incrementing = false;

After all those steps, every time new users registered it will automatically generate the UUID as their ID.

With auto increments, the user ID will be shown like this:

ID name
1 John
2 Doe

With UUID, the user ID will became like this:

ID                                    name
f2e54443-6d8d-45da-9b70-b3b2a5909131 John
7aae1e06-04f6-41a7-8ca4-9c79fc8ee0c5 Doe

Laravel Story is a series of articles about Learning Laravel. You can fork the sources code from here:

https://github.com/krisnaw/LaravelStory

--

--

Krisna Wijaya

Software developer based in Bali, code with PHP & JavaScript+hosted on AWS, and Tech Writer :)