Anvil
Anvil - The mobile companion for Laravel Forge. Available now. Download for iOS

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

If you ever have the need for a UUID column on your models, you may as well use a trait to populate them in case you need the same functionality on other models in the future.

AR
Anthony Rappa
1 min read - 6,399 views -

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.

Read next

Pruning Laravel Models

In the latest version of Laravel 8, Eloquent models now come with a Prunable and MassPrunable trait to automatically delete models based on criteria.

AR
1 min read - 10,838 views -

Laravel Lockout v6.0.0

Laravel Lockout v6.0 is a major upgrade that expands the package from basic read-only mode to a full maintenance and access-control system. It now supports Laravel 11 and 12 and introduces 10 new features, including IP allow/deny lists with CIDR, role-based bypass rules, customizable responses, route and pattern whitelisting, automatic API handling, a health-check endpoint, configurable caching, a full event system, Artisan management commands, and a new maintenance view. With 77 tests, refined middleware, and improved code quality, v6.0 is production-ready and built for precise control during maintenance or emergencies.

5 min read - 2,712 views -