Snippet 2: Adding a UUID Trait to auto-populate uuid columns on model create

Snippet 2: Adding a UUID Trait to auto-populate uuid columns on model create


UUID's are a great way to add unique IDs to your columns that aren't in numeric order, to make it harder for people to guess the next row in your database.

If you have numeric primary keys in a URL on a user facing page, it would be easy for them to change the ID in the URL and attempt to get a resource that doesn't belong to them if you don't have the proper precautions in place.

Generally, I use UUIDs in place of IDs on forward facing URLs for this reason.

I keep a handy trait in my models directory to add this functionality to any model I need.

UUID Trait:

<?php

namespace App\Models\Traits;

use Illuminate\Support\Str;

trait Uuid
{
    public function scopeUuid($query, $uuid)
    {
        return $query->where($this->getUuidName(), $uuid);
    }

    public function getUuidName(): string
    {
        return property_exists($this, 'uuidName') ? $this->uuidName : 'uuid';
    }

    protected static function bootUuid(): void
    {
        static::creating(function ($model) {
            $model->{$model->getUuidName()} = Str::uuid();
        });
    }
}

This trait gives you the flexibility to specify the UUID column on a per-model basis, as well as specify how you want to generate those UUIDs.

First add the uuid column to your tables:

$table->uuid('uuid');

Then add the trait to your model:

<?php

class Post extends Model
{
    use Uuid;
}

When a new model is created, you do not need to specify a UUID to insert as it will happen automatically.

Anthony Rappa

By Anthony Rappa

Hello! I'm a full stack developer from Long Island, New York. Working mainly with Laravel, Tailwind, Livewire, and Alpine.js (TALL Stack). I share everything I know about these tools and more, as well as any useful resources I find from the community. You can find me on GitHub and LinkedIn.