DEV Community

Bervianto Leo Pratama
Bervianto Leo Pratama

Posted on • Originally published at Medium on

1

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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay