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

Uuid Encoding Laravel Package

eventsauce/uuid-encoding

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require eventsauce/uuid-encoding
    

    This auto-installs ramsey/uuid (v4.1+), the required dependency.

  2. First Use Case: Encode a UUID

    use EventSauce\UuidEncoding\UuidEncoder;
    
    $encoder = new UuidEncoder();
    $uuid = \Ramsey\Uuid\Uuid::uuid4(); // Requires ramsey/uuid
    $encoded = $encoder->encode($uuid); // Returns e.g., "6ba7b8109dad11d180b400c04fd430c8"
    
  3. First Use Case: Decode a UUID

    $decoded = $encoder->decode($encoded); // Returns \Ramsey\Uuid\Uuid
    
  4. Key Files to Explore

    • src/UuidEncoder.php: Core logic for encoding/decoding.
    • tests/: Unit tests for edge cases (e.g., invalid UUIDs).

Implementation Patterns

Workflows

  1. Event-Sourcing Integration Use the encoder to store UUIDs in event payloads (e.g., EventSaucePHP):

    $event = new UserCreated(
        id: $encoder->encode($uuid),
        name: "John Doe"
    );
    $eventStore->append($streamName, $event);
    
  2. Database Storage Store UUIDs as compact strings (e.g., VARCHAR(32)) and decode on retrieval:

    $storedEncoded = $encoder->encode($uuid);
    // Later...
    $uuid = $encoder->decode($storedEncoded);
    
  3. API Payloads Return encoded UUIDs in JSON responses:

    return response()->json([
        'id' => $encoder->encode($uuid),
        'name' => 'John Doe'
    ]);
    

Laravel-Specific Patterns

  • Service Provider Binding Register the encoder as a singleton:

    $this->app->singleton(UuidEncoder::class, function ($app) {
        return new UuidEncoder();
    });
    
  • Eloquent Accessors Auto-encode/decode UUIDs in models:

    protected $casts = ['id' => 'string'];
    
    public function getIdAttribute($value) {
        return $encoder = app(UuidEncoder::class)->decode($value);
    }
    
    public function setIdAttribute($value) {
        $this->attributes['id'] = app(UuidEncoder::class)->encode($value);
    }
    
  • Form Request Validation Validate UUID strings before decoding:

    public function rules() {
        return ['uuid' => 'required|string|uuid_format'];
    }
    
    public function withValidator($validator) {
        $validator->after(function ($validator) {
            $uuid = app(UuidEncoder::class)->decode($this->input('uuid'));
            // Additional logic...
        });
    }
    

Gotchas and Tips

Pitfalls

  1. Invalid UUIDs Decoding malformed strings throws \InvalidArgumentException. Always validate:

    try {
        $uuid = $encoder->decode($input);
    } catch (\InvalidArgumentException $e) {
        throw new \InvalidArgumentException("Invalid UUID format");
    }
    
  2. UUID Version Mismatch The encoder assumes UUIDv4. If using other versions (e.g., UUIDv3), decode may fail.

  3. Database Schema Conflicts Ensure your database column types match the encoded length (32 chars for base64url).

Debugging Tips

  • Log Raw vs. Encoded Compare raw and encoded UUIDs during debugging:

    \Log::debug("Raw UUID", [$uuid->toString()]);
    \Log::debug("Encoded UUID", [$encoder->encode($uuid)]);
    
  • Test Edge Cases Validate with:

    • Nil/empty strings.
    • Non-UUID strings (e.g., "not-a-uuid").
    • UUIDs with hyphens (e.g., "123e4567-e89b-12d3-a456-426614174000").

Performance Considerations

  • Benchmark Encoding/Decoding Test in hot paths (e.g., event publishing):

    $start = microtime(true);
    $encoded = $encoder->encode($uuid);
    $time = microtime(true) - $start;
    \Log::debug("Encoding time: {$time}s");
    
  • Caching Cache decoded UUIDs if reused frequently (e.g., in request handlers).

Extension Points

  1. Custom Encoders Extend UuidEncoder for alternative formats (e.g., hex):

    class HexUuidEncoder extends UuidEncoder {
        public function encode(\Ramsey\Uuid\UuidInterface $uuid): string {
            return $uuid->toString();
        }
    }
    
  2. Fallback Logic Implement a fallback for unsupported UUIDs:

    $uuid = $encoder->decode($encoded) ?? \Ramsey\Uuid\Uuid::fromString($encoded);
    
  3. Laravel Facades Create a facade for cleaner syntax:

    // app/Facades/UuidEncoder.php
    public static function encode($uuid) {
        return app(UuidEncoder::class)->encode($uuid);
    }
    

    Usage:

    $encoded = \UuidEncoder::encode($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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor