hidehalo/nanoid-php
Secure, URL-friendly unique ID generator for PHP inspired by nanoid. Generates 21‑char IDs with UUIDv4-like collision probability, supports custom alphabets/lengths, and lets you plug in your own random bytes generator for extra control.
Installation
composer require hidehalo/nanoid-php:^2.0
Note: Version 2.0 drops support for PHP < 7.1. Ensure your Laravel project meets this requirement.
First Use Case Generate a URL-safe ID in a Laravel controller:
use NanoId\NanoId;
$nanoId = new NanoId();
$id = $nanoId->generate(); // e.g., "V1StGXR8_Z5jdHi6B-myT"
Where to Look First
src/NanoId.php for core logic (verify PHP 8.2+ compatibility)tests/ for edge cases and PHP 8.2/8.3-specific testsBasic ID Generation (PHP 8.2+)
$nanoId = new NanoId(); // Default: 21 chars, alphanumeric + '-'
$id = $nanoId->generate();
Custom Length & Alphabet (PHP 8.2+)
$customId = new NanoId(10, NanoId::ALPHABET_NO_DASH);
$id = $customId->generate();
Integration with Eloquent Models (Laravel 9+)
use Illuminate\Database\Eloquent\Model;
use NanoId\NanoId;
class Post extends Model {
protected static function boot() {
static::creating(function ($model) {
$nanoId = new NanoId(10);
$model->uuid = $nanoId->generate();
});
}
}
URL-Safe Slugs (PHP 8.2+)
$slugId = new NanoId(8, NanoId::ALPHABET_LOWER);
$slug = $slugId->generate(); // e.g., "aBc123xy"
Batch Generation (PHP 8.2+)
$batch = new NanoId();
$ids = array_map(fn() => $batch->generate(), range(1, 100));
Service Provider Binding (PHP 8.2+)
// app/Providers/AppServiceProvider.php
public function register() {
$this->app->singleton(NanoId::class, function ($app) {
return new NanoId(16, NanoId::ALPHABET_NO_DASH);
});
}
Request-Based IDs (Laravel 9+)
// app/Http/Controllers/PostController.php
public function store(Request $request) {
$nanoId = new NanoId(12);
$request->merge(['uuid' => $nanoId->generate()]);
}
Migration UUID Columns (PHP 8.2+)
Schema::create('posts', function (Blueprint $table) {
$table->string('uuid', 255)->unique(); // Wider than default VARCHAR(255) if needed
$table->timestamps();
});
API Response IDs (PHP 8.2+)
return response()->json([
'data' => [
'id' => $nanoId->generate(),
'title' => 'Example Post',
]
]);
PHP Version Drop (Breaking Change)
2.0 drops support for PHP < 7.1.1.x branch if using PHP < 7.1.Collision Risk (Unchanged)
$nanoId = new NanoId(10);
$ids = [];
do {
$id = $nanoId->generate();
if (in_array($id, $ids, true)) {
throw new \RuntimeException("Collision detected!");
}
$ids[] = $id;
} while (count($ids) < 100000);
Alphabet Confusion (Unchanged)
ALPHABET_NO_DASH removes - but keeps 0-9a-zA-Z. For stricter URL safety, combine with ALPHABET_LOWER:
$alphabet = NanoId::ALPHABET_LOWER . NanoId::ALPHABET_NO_DASH;
$nanoId = new NanoId(10, $alphabet);
Database Indexing (Unchanged)
VARCHAR(255)).PHP 8.4 Deprecation Warnings (Fixed in 2.0)
2.0 for full PHP 8.4 compatibility.Validate Generated IDs (PHP 8.2+)
$nanoId = new NanoId();
$id = $nanoId->generate();
assert(strlen($id) === 21); // Default length
assert(preg_match('/^[0-9A-Za-z_-]+$/', $id));
Check Alphabet (PHP 8.2+)
$nanoId = new NanoId(10, NanoId::ALPHABET_LOWER);
$id = $nanoId->generate();
assert(preg_match('/^[a-z0-9]+$/', $id)); // No uppercase or dashes
Performance Benchmarking (PHP 8.2+)
$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
$nanoId->generate();
}
$time = microtime(true) - $start;
echo "Generated 10k IDs in {$time}s"; // Should be < 0.5s
Custom ID Formats (PHP 8.2+)
Extend NanoId to support formats like:
class CustomNanoId extends NanoId {
public function generateWithPrefix() {
return 'ID-' . parent::generate();
}
}
Caching Layer (Laravel 9+) Cache frequently used IDs:
$cache = app(\Illuminate\Cache\CacheManager::class)->store('file');
$id = $cache->remember('nanoid::unique', 60, function () {
return (new NanoId())->generate();
});
Integration with Laravel Scout (PHP 8.2+) Use NanoIDs as searchable keys:
Scout::model('Post')->searchableAs('uuid');
Environment-Specific Config (PHP 8.2+)
$length = config('nanoid.length', 21);
$nanoId = new NanoId($length);
Add to config/nanoid.php:
return [
'length' => env('NANOID_LENGTH', 21),
'alphabet' => env('NANOID_ALPHABET', NanoId::ALPHABET),
];
Event-Based Generation (Laravel 9+) Trigger ID generation via Laravel events:
// In a service provider
Event::listen(\Illuminate\Database\Eloquent\Model::creating, function ($model) {
$model->uuid = (new NanoId())->generate();
});
How can I help you explore Laravel packages today?