Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Model Uuid Laravel Package

dyrynda/laravel-model-uuid

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dyrynda/laravel-model-uuid
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Dyrynda\\ModelUuid\\ModelUuidServiceProvider" --tag="config"
    
  2. Enable UUIDs for a Model: Use the HasUuid trait in your Eloquent model:

    use Dyrynda\\ModelUuid\\Traits\\HasUuid;
    
    class User extends Model
    {
        use HasUuid;
    }
    
  3. First Use Case:

    • Migrate your database to use uuid type (e.g., uuid() in Laravel migrations).
    • Run migrations, and the package will automatically handle UUID generation on model creation.

Implementation Patterns

Core Workflows

  1. UUID Generation:

    • Automatically generates UUIDs on create() if id is not set.
    • Customize generation via getUuid() method override:
      public function getUuid()
      {
          return Str::uuid()->toString(); // Custom logic
      }
      
  2. Querying with UUIDs:

    • Use UUIDs in queries like any other field:
      $user = User::where('uuid', $uuid)->first();
      
    • Works seamlessly with Laravel’s query builder and Eloquent.
  3. Relationships:

    • Foreign keys can use UUIDs (ensure database schema supports it).
    • Define relationships as usual:
      public function posts()
      {
          return $this->hasMany(Post::class);
      }
      
  4. API Responses:

    • UUIDs are returned in JSON responses by default (no extra config needed).
    • Override toArray() or toJson() if customization is required.

Integration Tips

  • Database Schema: Use uuid() in migrations (Laravel 8+):

    Schema::create('users', function (Blueprint $table) {
        $table->uuid('id')->primary();
        // ...
    });
    

    For older Laravel versions, use string(36) and cast to UUID in the model.

  • Seeding: UUIDs are auto-generated, but you can manually set them in seeders:

    User::create(['uuid' => Str::uuid(), 'name' => 'Test']);
    
  • Testing: Mock UUID generation in tests:

    $this->partialMock(User::class, function ($mock) {
        $mock->shouldReceive('getUuid')->andReturn('test-uuid');
    });
    

Gotchas and Tips

Pitfalls

  1. Database Compatibility:

    • Ensure your database supports UUIDs (PostgreSQL, MySQL 8+, SQLite with extensions).
    • For MySQL < 8.0, use char(36) and cast to UUID in the model:
      protected $casts = ['uuid' => 'string'];
      
  2. Primary Key Conflicts:

    • If id is not nullable, ensure UUIDs are generated before saving:
      $user = new User();
      $user->forceFill(['uuid' => Str::uuid()]);
      $user->save();
      
  3. Soft Deletes:

    • UUIDs work with soft deletes, but ensure your deleted_at column is not a UUID.
  4. Caching:

    • UUIDs are less cache-friendly than auto-increment IDs. Use uuid() in cache keys if needed:
      Cache::put("user_{$user->uuid}", $data, $minutes);
      

Debugging

  • UUID Not Generated: Check if HasUuid trait is applied and uuid column exists in the database. Verify no custom getIncrementing() or getKeyType() overrides conflict.

  • Query Issues: Use toSql() on queries to debug UUID filtering:

    \Log::info(User::where('uuid', $uuid)->toSql());
    

Extension Points

  1. Custom UUID Generation: Override getUuid() or use a custom generator:

    use Ramsey\Uuid\Uuid;
    
    public function getUuid()
    {
        return Uuid::uuid4()->toString();
    }
    
  2. UUID Validation: Add validation rules in rules() or validate():

    use Dyrynda\\ModelUuid\\Rules\\Uuid;
    
    $request->validate([
        'uuid' => ['required', new Uuid],
    ]);
    
  3. UUID Formatting: Customize UUID output (e.g., hyphenated vs. non-hyphenated):

    public function getAttribute($key)
    {
        if ($key === 'uuid') {
            return str_replace('-', '', parent::getAttribute($key));
        }
        return parent::getAttribute($key);
    }
    
  4. UUID as Foreign Key: Use uuid() for foreign keys in migrations and define relationships normally:

    public function owner()
    {
        return $this->belongsTo(User::class, 'owner_id', 'uuid');
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope