Installation:
composer require wooserv/laravel-objectid
No additional configuration is needed—auto-discovery handles setup.
First Use Case:
$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();
});
Generate IDs Manually:
Use the global objectid() helper anywhere in your app:
$newId = objectid(); // Returns a 24-char ObjectId string
Model Lifecycle Integration:
create() and save() (if not provided).incrementing and hasGlobalScopes features.$user = User::create(['name' => 'John']); // Auto-assigns ObjectId
Migrations and Schema:
$table->objectId() for primary/foreign keys:
$table->objectId('user_id')->foreign()->constrained();
$table->objectId('id')->unsignedIndex()).Querying:
User::where('id', objectid())->first(); // Works as expected
User::orderBy('id', 'asc')).Helper Function:
objectid() in controllers, services, or tests:
$id = objectid(); // Generates a new ObjectId
$exists = User::where('id', $id)->exists(); // Check uniqueness
objectId() in migrations to avoid type mismatches.objectid() in factories/seeds for deterministic test data:
User::factory()->create(['id' => objectid()]);
Database Compatibility:
VARCHAR(24)). Ensure your DB schema matches:
$table->string('id', 24)->primary(); // Fallback if $table->objectId() isn’t supported
CHAR(24) under the hood for efficiency (not VARCHAR).Type Casting:
// ❌ Wrong: Assumes ObjectId is numeric
$userId = (int) $user->id; // Loses data!
// ✅ Correct: Use as string
$userId = $user->id; // Returns "507f1f77bcf86cd799439011"
Migration Conflicts:
objectId() to an existing table, run:
php artisan migrate
The package handles schema updates automatically.Performance:
Validation Errors:
string (or objectId() in migrations).VARCHAR(24)).dd(objectid()); // Verify output is 24 chars
Duplicate IDs:
$testId = objectid('fixed_seed'); // For reproducible tests
Custom Generation:
config/objectid.php:
'generator' => \Wooserv\ObjectId\Generators\CustomGenerator::class,
Wooserv\ObjectId\Contracts\Generator for custom logic.Schema Macros:
objectId() macro in AppServiceProvider:
use Wooserv\ObjectId\ObjectId;
ObjectId::macro('customOption', function () {
return 'default_value';
});
Testing:
objectid() helper in tests:
$this->app->instance('objectid', fn() => 'mocked_id_123');
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
How can I help you explore Laravel packages today?