Laravel 8 Use uuid as Primary Key Example

Laravel 8 use uuid as primary key is the todays tutorial. We all know that id is the default primary key in Laravel. But in this how to use uuid in laravel 8 example, we will create our custom primary key using uuid.

If you don't know how to use uuid in laravel 8 then this will be the perfect tutorial that what are you looking for. So in this laravel 8 uuid primary key tutorial, you will learn it from step by step.

We only need some steps to change your Model to use UUID as default primary key. Let's see the example code:


namespace App\Traits;

use Illuminate\Support\Str;

trait Uuid
    protected static function 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());


Now we have use this trait in your model where you want uuid as primary key. So see the code to understand:


namespace App;

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

class User extends Authenticatable
    Use Uuid, Notifiable;
    public $incrementing = false;

    protected $keyType = 'uuid';



 Now use in your migration like below:

public function up()
    Schema::create('users', function (Blueprint $table) {
        // another column



Read also : When and How to Use @class Blade Directive in Laravel


Hope it can help you.


Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js