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

Id Encoding Laravel Package

eventsauce/id-encoding

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require eventsauce/id-encoding
    

    This auto-installs ramsey/uuid (v4.1+) as a dependency.

  2. First Use Case: Encode/Decode UUIDs

    use EventSauce\IdEncoding\IdEncoder;
    use Ramsey\Uuid\Uuid;
    
    $encoder = new IdEncoder();
    $uuid = Uuid::uuid4();
    
    // Encode UUID to URL-safe string (e.g., "a1b2c3d4-5678-90ef-ghij-klmnopqrstuv")
    $encodedId = $encoder->encode($uuid);
    
    // Decode back to UUID
    $decodedUuid = $encoder->decode($encodedId);
    
  3. Where to Look First


Implementation Patterns

Laravel-Specific Workflows

  1. Eloquent Model Integration Add accessors/mutators to encode/decode IDs automatically:

    // app/Models/Event.php
    use EventSauce\IdEncoding\IdEncoder;
    
    class Event extends Model {
        public function getEncodedIdAttribute(): string {
            return app(IdEncoder::class)->encode($this->id);
        }
    
        public function setEncodedIdAttribute(string $encodedId): void {
            $this->id = app(IdEncoder::class)->decode($encodedId);
        }
    }
    
  2. API Resource Transformation Use encoded IDs in API responses:

    // app/Http/Resources/EventResource.php
    public function toArray($request) {
        return [
            'id' => $this->whenLoaded('id', fn () => $this->encoded_id),
            'title' => $this->title,
        ];
    }
    
  3. Service Container Binding Register the encoder in AppServiceProvider:

    public function register() {
        $this->app->singleton(IdEncoder::class, function ($app) {
            return new \EventSauce\IdEncoding\IdEncoder();
        });
    }
    
  4. Event/Queue Payloads Encode IDs for event payloads or queue jobs:

    // app/Events/OrderCreated.php
    public function __construct(
        public string $encodedOrderId,
        public string $customerId
    ) {}
    
    // Usage:
    $encodedId = app(IdEncoder::class)->encode($order->id);
    event(new OrderCreated($encodedId, $customerId));
    

Advanced Patterns

  1. Custom ID Types Extend IdEncoder for non-UUID IDs (e.g., integers):

    class IntegerIdEncoder extends \EventSauce\IdEncoding\IdEncoder {
        public function encode($id): string {
            return base64_encode((string) $id);
        }
    
        public function decode(string $encoded): int {
            return (int) base64_decode($encoded);
        }
    }
    
  2. Database Storage Store encoded IDs in VARCHAR columns (e.g., encoded_id VARCHAR(22) for Base64 UUIDs):

    // Migration
    Schema::table('events', function (Blueprint $table) {
        $table->string('encoded_id')->unique();
    });
    
  3. URL Generation Use encoded IDs in routes or redirects:

    Route::get('/events/{encodedId}', [EventController::class, 'show']);
    // Generate URL:
    $url = route('events.show', ['encodedId' => $event->encoded_id]);
    

Gotchas and Tips

Pitfalls

  1. UUID Dependency

    • The package requires ramsey/uuid. If you’re not using UUIDs, avoid this package (use a custom encoder instead).
    • Fix: Check composer.json for ramsey/uuid bloat if optimizing for size.
  2. Database Queries

    • Encoded IDs are strings. Ensure queries use proper casting:
      // Wrong (compares string to UUID):
      $events = Event::where('id', $encodedId)->get();
      
      // Correct (decode first or use raw UUID):
      $events = Event::where('id', app(IdEncoder::class)->decode($encodedId))->get();
      
    • Tip: Add a computed column or index for encoded IDs if querying frequently.
  3. Malformed Input

    • Decoding invalid strings throws exceptions. Validate input:
      try {
          $decoded = $encoder->decode($encodedId);
      } catch (\InvalidArgumentException $e) {
          abort(400, 'Invalid ID format');
      }
      
  4. Performance in Loops

    • Avoid encoding/decoding in tight loops (e.g., API responses). Cache results:
      $encodedIds = collect($events)->map(fn ($event) => cache()->remember(
          "encoded_id_{$event->id}",
          now()->addHours(1),
          fn () => app(IdEncoder::class)->encode($event->id)
      ));
      

Debugging Tips

  1. Log Raw vs. Encoded IDs Compare raw and encoded IDs during transitions:

    \Log::debug('Raw ID', ['raw' => $event->id, 'encoded' => $event->encoded_id]);
    
  2. Test Edge Cases

    • Empty strings, non-UUID inputs, or malformed Base64.
    • Use the package’s tests as a reference:
      $this->assertEquals($uuid, $encoder->decode($encoder->encode($uuid)));
      
  3. Check for Silent Failures

    • Ensure decode() throws exceptions for invalid input (default behavior).

Configuration Quirks

  1. Default Encoding Scheme

    • The package uses Base64URL by default (URL-safe). Override in a custom encoder if needed:
      class CustomEncoder extends IdEncoder {
          public function encode($id): string {
              return base32_encode($id); // Alternative scheme
          }
      }
      
  2. Laravel Caching

    • Cache encoded IDs in Redis/Memcached to avoid repeated encoding:
      $encodedId = cache()->remember(
          "encoded_id_{$model->id}",
          now()->addHours(1),
          fn () => app(IdEncoder::class)->encode($model->id)
      );
      
  3. Migration Strategy

    • If migrating from raw UUIDs to encoded strings:
      • Add a temporary column for encoded IDs.
      • Backfill data during downtime or in batches.
      • Drop the old column after validation.

Extension Points

  1. Custom Encoders Extend IdEncoder for project-specific needs:

    class ProjectIdEncoder extends IdEncoder {
        public function encode($id): string {
            return strtoupper(md5($id)); // Custom logic
        }
    }
    
  2. Laravel Macros Add helper methods to the IdEncoder facade:

    IdEncoder::macro('encodeUuid', function ($uuid) {
        return $this->encode($uuid);
    });
    
  3. EventSauce Integration If using EventSaucePHP/EventSauce, configure the encoder in the event store:

    $eventStore = new \EventSauce\EventStore\EventStore(
        new \EventSauce\EventStore\Persistence\MySql\MySqlEventRepository(
            new \EventSauce\EventStore\Persistence\MySql\Connection($pdo),
            new \EventSauce\EventStore\Persistence\MySql\Schema($pdo),
            new \EventSauce\EventStore\Persistence\MySql\EventSerializer(
                app(IdEncoder::class) // Inject encoder
            )
        )
    );
    

Laravel-Specific Tips

  1. Use Facades for Convenience Create a facade to simplify usage:

    // app/Facades/IdEncoder.php
    namespace App\Facades;
    
    use Illuminate\Support\Facades\Facade;
    
    class IdEncoder extends Facade {
        protected static function getFacadeAccessor() {
            return \EventSauce\IdEncoding\IdEncoder::class;
        }
    }
    

    Now use IdEncoder::encode($id) globally.

  2. Model Observers Automate encoding/decoding on save:

    // app/Observers/EventObserver.php
    class EventObserver {
        public function saving(Event $event) {
            if (!$event->encoded_id && $event->id) {
                $
    
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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