Date
1 min read

Generating and Enforcing UUIDs in Laravel for Immutable Model IDs

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

trait HasUuid
{
    /**
     * Generate a new UUID for the given model.
     *
     * @return void
     */
    public static function bootHasUuid(): void
    {
        static::creating(function (Model $model) {
			$model->uuid = self::generateUuid();
        });

        static::updating(function (Model $model) {
            if (empty($model->uuid)) {
                $model->uuid = self::generateUuid();
            }
        });
    }

    /**
     * Generate a random UUID.
     *
     * @return string
     */
    public static function generateUuid(): string
    {
        do {
            $uuid = (string) Str::uuid();
            $exists = self::where('uuid', $uuid)->exists();
        } while ($exists);

        return $uuid;
    }
}

You might also like...

  • Read article

    Simple breadcrumbs in Laravel

    Breadcrumbs are a crucial navigation element in web applications, providing users with a clear path to follow within your site's hierarchy. By the end, you'll have an easy-to-use breadcrumb system that enhances your site's user experience.

  • Read article

    Laravel update multiple rows with different values

    Discover efficient techniques for updating multiple rows with unique values in Laravel. Explore step-by-step instructions and practical examples to streamline your database operations.

  • Read article

    Exporting large amounts of data in Laravel

    An opinionated approach on how best to handle exporting large amounts of data in Laravel using commands and queues.

Let's work together 🤝

Line
Christopher Kelker

Chriscreates