laravel-model-uuid

repository·main·Indexed 19 days ago

https://github.com/michaeldyrynda/laravel-model-uuid

A Laravel package for UUID generation and management in Eloquent models. It supports multiple UUID versions (v1, v4, v6, v7, and ordered), binary storage optimization via the EfficientUuid caster and efficientUuid migration macro, and provides traits for automatic generation, route model binding, and binary UUID relationship handling.

Tokens
2.2K
Snippets
12
Records
13
Agent score
66%

What's inside laravel-model-uuid

  1. Handle Binary UUID relationships

    main

    When storing UUIDs as binary (e.g., using EfficientUuid cast with BINARY(16) columns), standard Eloquent relationships will fail because Laravel passes strings instead of binary data.

    To fix this, you must add the Dyrynda\Database\Support\UsesBinaryUuidBuilder trait to every model in the relationship chain that uses binary UUID columns.

    // In the parent model
    class User extends Model
    {
        use GeneratesUuid, UsesBinaryUuidBuilder;
    
        public function posts() { return $this->hasMany(Post::class); }
    }
    
    // In the child model
    class Post extends Model
    {
        use GeneratesUuid, UsesBinaryUuidBuilder;
    
        public function user() { return $this->belongsTo(User::class); }
    }
  2. Use UUID as a Primary Key

    main

    If you choose to use a UUID as your primary id column, you must disable auto-incrementing and set the key type to string to prevent Laravel from casting the UUID to an integer.

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use Dyrynda\Database\Support\GeneratesUuid;
    
    class Post extends Model
    {
        use GeneratesUuid;
    
        public $incrementing = false;
    
        protected $keyType = 'string';
    }
  3. Use the GeneratesUuid trait in Eloquent models

    main

    To enable automatic UUID generation, import and use the Dyrynda\Database\Support\GeneratesUuid trait in your model. By default, it expects a column named uuid to exist in your database.

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use Dyrynda\Database\Support\GeneratesUuid;
    
    class Post extends Model
    {
        use GeneratesUuid;
    }
  4. Query records using UUID scopes

    main

    The GeneratesUuid trait provides whereUuid and whereNotUuid scopes. These scopes automatically respect your custom column configuration.

    // Using default 'uuid' column
    $post = Post::whereUuid($uuid)->first();
    $posts = Post::whereNotUuid([$uuid1, $uuid2])->get();
    
    // Using a specific custom column
    $post = Post::whereUuid($uuid, 'custom_column')->first();
    $posts = Post::whereNotUuid([$uuid1, $uuid2], 'custom_column')->get();
  5. Enable implicit Route Model Binding for UUIDs

    main

    To use implicit route model binding on your UUID field, use the Dyrynda\Database\Support\BindsOnUuid trait. This will use the column defined by uuidColumn() by default.

    // app/Providers/RouteServiceProvider.php
    public function boot()
    {
        Route::bind('post', function ($post) {
            return \App\Post::whereUuid($post)->first();
        });
    }
  6. Configure custom UUID columns

    main

    You can customize which column(s) store the UUID values by overriding specific methods in your model:

    • uuidColumn(): Returns a string for a single custom column name.
    • uuidColumns(): Returns an array of column names if a table has multiple UUID columns.
    class Post extends Model
    {
        // Single custom column
        public function uuidColumn(): string
        {
            return 'custom_column';
        }
    
        // Multiple UUID columns
        public function uuidColumns(): array
        {
            return ['uuid', 'custom_column'];
        }
    }
  7. Configure UUID versions

    main

    The package supports uuid1, uuid4, uuid6, ordered (Laravel's ordered UUID v4), and uuid7.

    You can set the version in two ways:

    1. Per-model: Override the uuidVersion() method.
    2. Globally: Set the uuid_version key in config/model-uuid.php.

    Per-model settings take priority over the global configuration.

    // Per-model configuration
    class Post extends Model
    {
        use GeneratesUuid;
    
        public function uuidVersion(): ?string
        {
            return 'uuid7';
        }
    }
    
    // Global configuration in config/model-uuid.php
    return [
        'uuid_version' => 'uuid4',
    ];
  8. Use efficientUuid in database migrations

    main

    The package extends Laravel's Blueprint class with an efficientUuid macro. This allows you to define UUID columns using a database-optimized format (e.g., binary for MySQL, bytea for PostgreSQL, or blob for SQLite) instead of standard string-based UUIDs. This is useful for reducing storage requirements and improving indexing performance.

    Schema::create('users', function (Blueprint $table) {
        $table->efficientUuid('id')->primary();
        // ...
    });
  9. Use EfficientUuid for binary UUID casting

    main

    The EfficientUuid class is an Eloquent attribute caster designed to handle UUIDs stored in a binary format in the database. It automatically converts between a string representation (e.g., 550e8400-e29b-41d4-a716-446655440000) when accessing the model attribute and the raw bytes when saving to the database. This is highly efficient for storage and indexing in databases like MySQL or PostgreSQL.

    To use it, add it to the $casts array in your Eloquent model.

    use Dyrynda\Database\Support\Casts\EfficientUuid;
    
    class User extends Model
    {
        protected $casts = [
            'uuid' => EfficientUuid::class,
        ];
    }