DEV Community

Bervianto Leo Pratama
Bervianto Leo Pratama

Posted on • Originally published at Medium on

Setup UUID as Primary Key in Laravel 7

In case you never heard about Laravel, you can visit here.

Photo by Christopher Gower on Unsplash

Default primary key for Laravel Model is using increment integer, for reference. In some case, developer want to use another type such as UUID. What is UUID? In short, UUID stands for Universally Unique IDentifier , for more explanation, please read also here.

You only need some steps to change your Model so use UUID as default.

  1. Create Uuid Trait, for example I place the file in App\Traits with name Uuid.php. In this example, we use id column as our primary key, you can use another column as your want.

Notes: In case you want to know what is trait, read [_here](https://www.php.net/manual/en/language.oop5.traits.php)._

<?php

namespace App\Traits;

use Illuminate\Support\Str;

trait Uuid
{
    protected static function boot()
    {
        parent::_boot_();

        static::_creating_(function ($model) {
            try {
 **$model->id = (string) Str::_uuid_(); // generate uuid**  
                // Change id with your primary key
            } catch (UnsatisfiedDependencyException $e) {
                abort(500, $e->getMessage());
            }
        });
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Change your Model, for example we change User class. Here the change
<?php

namespace App;

use App\Traits\Uuid;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends _Authenticatable_
{
  **Use Uuid;**  
    use Notifiable;

    _/\*\*  
 \* Indicates if the IDs are auto-incrementing.  
 \*  
 \*_ **_@var_** _bool  
 \*/_ **public $incrementing = false;**  

    _/\*\*  
 \* The "type" of the auto-incrementing ID.  
 \*  
 \*_ **_@var_** _string  
 \*/_ **protected $keyType = 'uuid';**

    // ...
}
Enter fullscreen mode Exit fullscreen mode
  1. Change your migrationsfiles, because we use users, here the example changes.
_/\*\*  
 \* Run the migrations.  
 \*  
 \*_ **_@return_** _void  
 \*/_ public function up()
{
    Schema::_create_('users', function (Blueprint $table) {
 **$table->uuid('id')->primary(); // define your primary key column**  
        // another column
    });

}

 **$table->uuid('id')->primary();**  
        // another column
    });

}
Enter fullscreen mode Exit fullscreen mode

Hopefully this will help you.

For another Models that use same column, you can reuse the Uuid trait and do some change same with step 2 and 3.

Top comments (0)