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 Objectid Laravel Package

wooserv/laravel-objectid

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require wooserv/laravel-objectid
    

    No additional configuration is needed—auto-discovery handles setup.

  2. First Use Case:

    • Migrations: Replace $table->id() with $table->objectId() in your migration files.
      Schema::create('users', function (Blueprint $table) {
          $table->objectId('id')->primary(); // Auto-generates 24-char ObjectId
          $table->string('name');
          $table->timestamps();
      });
      
    • Models: No changes required—ObjectId is automatically cast to a string when accessed.
  3. Generate IDs Manually: Use the global objectid() helper anywhere in your app:

    $newId = objectid(); // Returns a 24-char ObjectId string
    

Implementation Patterns

Workflows

  1. Model Lifecycle Integration:

    • ObjectIds are auto-generated on create() and save() (if not provided).
    • Works seamlessly with Eloquent’s incrementing and hasGlobalScopes features.
    • Example:
      $user = User::create(['name' => 'John']); // Auto-assigns ObjectId
      
  2. Migrations and Schema:

    • Use $table->objectId() for primary/foreign keys:
      $table->objectId('user_id')->foreign()->constrained();
      
    • Supports unsigned indexes (e.g., $table->objectId('id')->unsignedIndex()).
  3. Querying:

    • ObjectIds are cast to strings, so standard Eloquent queries work:
      User::where('id', objectid())->first(); // Works as expected
      
    • For sorting, leverage the timestamp-encoded prefix (e.g., User::orderBy('id', 'asc')).
  4. Helper Function:

    • Use objectid() in controllers, services, or tests:
      $id = objectid(); // Generates a new ObjectId
      $exists = User::where('id', $id)->exists(); // Check uniqueness
      

Integration Tips

  • Foreign Keys: Ensure foreign keys use objectId() in migrations to avoid type mismatches.
  • APIs: Return ObjectIds as strings in JSON responses (no extra casting needed).
  • Testing: Use objectid() in factories/seeds for deterministic test data:
    User::factory()->create(['id' => objectid()]);
    
  • Caching: ObjectIds are compact (24 chars) and sortable, ideal for cache keys or Redis hashes.

Gotchas and Tips

Pitfalls

  1. Database Compatibility:

    • ObjectIds are stored as strings in the database (e.g., VARCHAR(24)). Ensure your DB schema matches:
      $table->string('id', 24)->primary(); // Fallback if $table->objectId() isn’t supported
      
    • MySQL: Uses CHAR(24) under the hood for efficiency (not VARCHAR).
  2. Type Casting:

    • ObjectIds are always returned as strings in Eloquent. Avoid treating them as integers or binary data.
    • Example of a common mistake:
      // ❌ Wrong: Assumes ObjectId is numeric
      $userId = (int) $user->id; // Loses data!
      
      // ✅ Correct: Use as string
      $userId = $user->id; // Returns "507f1f77bcf86cd799439011"
      
  3. Migration Conflicts:

    • If you add objectId() to an existing table, run:
      php artisan migrate
      
      The package handles schema updates automatically.
  4. Performance:

    • ObjectIds are 3× faster to generate than UUIDs (per package claims). Benchmark in high-throughput apps.

Debugging

  • Validation Errors:

    • If ObjectIds fail validation, ensure:
      • The column type is string (or objectId() in migrations).
      • The length is exactly 24 characters (e.g., VARCHAR(24)).
    • Debug with:
      dd(objectid()); // Verify output is 24 chars
      
  • Duplicate IDs:

    • ObjectIds are globally unique (like UUIDs), but collisions are theoretically possible. Use the helper’s deterministic generation for testing:
      $testId = objectid('fixed_seed'); // For reproducible tests
      

Extension Points

  1. Custom Generation:

    • Override the default generator in config/objectid.php:
      'generator' => \Wooserv\ObjectId\Generators\CustomGenerator::class,
      
    • Implement Wooserv\ObjectId\Contracts\Generator for custom logic.
  2. Schema Macros:

    • Extend the objectId() macro in AppServiceProvider:
      use Wooserv\ObjectId\ObjectId;
      
      ObjectId::macro('customOption', function () {
          return 'default_value';
      });
      
  3. Testing:

    • Mock the objectid() helper in tests:
      $this->app->instance('objectid', fn() => 'mocked_id_123');
      

Pro Tips

  • Sorting: ObjectIds encode a timestamp in the first 4 bytes. Sort by id to get chronological order:

    User::orderBy('id', 'asc')->get(); // Oldest first
    
  • URLs/Slugs: Use ObjectIds as slugs or short URLs (e.g., /users/{objectId}). They’re URL-safe and compact.

  • Legacy Systems: To migrate from UUIDs to ObjectIds:

    $user->id = objectid(); // Replace UUID with ObjectId
    $user->save(); // Updates the string column
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui