I'm currently available for full time hire! Inquire Here

This post is more than a year old. There is a chance the content is outdated.

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:

1<?php
2 
3namespace App\Models\Traits;
4 
5use Illuminate\Support\Str;
6 
7trait Uuid
8{
9 public function scopeUuid($query, $uuid)
10 {
11 return $query->where($this->getUuidName(), $uuid);
12 }
13 
14 public function getUuidName(): string
15 {
16 return property_exists($this, 'uuidName') ? $this->uuidName : 'uuid';
17 }
18 
19 protected static function bootUuid(): void
20 {
21 static::creating(function ($model) {
22 $model->{$model->getUuidName()} = Str::uuid();
23 });
24 }
25}

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:

1$table->uuid('uuid');

Then add the trait to your model:

1<?php
2 
3class Post extends Model
4{
5 use Uuid;
6}

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.