How to use uuid as Primary Key in Laravel Example

laravel uuid as primary key example; In this tutorial you will learn how to use uuid as a primary key in laravel applicaiton. We all know that id is the default primary key in Laravel but we can use custom primary key as uuid.

UUIDs (Universally Unique Identifier) are 128 bits values, used to uniquely identify the table records. They are commonly represented as a hexadecimal string split into five groups separated by hyphens.

If you don’t know how to use uuid in laravel 9 then this will be the perfect tutorial that what are you looking for. Let’s see the step by step guid for how to create uuid and set primary key in laravel.

A typical example of UUID looks like:

116c34de-3dcb-44bc-9511-a48242b9aaab

Set uuid in Migration File

First we will set uuid as a primary key in laravel migration.

Schema::create('posts', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('title');
    $table->text('body');
    $table->timestamps();
});

Add Trait for Generate uuid as Primary Key

Now create a trait named as ‘Uuid’ and put the below code on it, The trait generate a new primary key uuid.

App\Traits\Uuid.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());
            }
        });
    }
}

Update Trait in Model

Now use the trait to your model and set primary key as uuid and keytype to string and auto increment to false, because the uuid is generate as a string which is 32 character long.

App\Models\Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Traits\Uuid;

class Post extends Model
{
    use HasFactory, Uuid;
    protected $fillable = [
        'id', 'title', 'body' 
    ];

    protected $primaryKey = 'uuid';
    protected $keyType = 'string';
    public $incrementing = false;
}

Hope it can help you, for more follow us on social networks.

Leave a Comment