Installation
composer require parables/laravel-cuid2
Publish the config (optional):
php artisan vendor:publish --provider="Parables\LaravelCuid2\LaravelCuid2ServiceProvider" --tag="config"
First Use Case
Add the HasCuid2 trait to your Eloquent model:
use Parables\LaravelCuid2\HasCuid2;
class Post extends Model
{
use HasCuid2;
}
The package automatically adds a cuid column to your migration (if missing) and handles generation.
Key Config
Check config/cuid2.php for:
column_name (default: cuid)generate_on_create (default: true)generate_on_update (default: false)Basic Usage
$post = Post::create(['title' => 'Hello World']);
// $post->cuid is now a Cuid2 string (e.g., "cl7x89q0x000008l10000001")
Manual Generation
$cuid = \Parables\LaravelCuid2\Facades\Cuid2::generate();
$post = Post::create(['title' => 'Manual Cuid', 'cuid' => $cuid]);
Querying by Cuid
$post = Post::where('cuid', 'cl7x89q0x000008l10000001')->first();
// Add index to `cuid` column in your migration for performance:
$table->string('cuid')->unique()->index();
Custom Column Names
class Post extends Model
{
use HasCuid2;
protected $cuidColumn = 'custom_id';
}
cuid in JSON responses for client-side use.
$post->append('cuid'); // Ensure it's included in `toArray()`.
cuid as a foreign key in polymorphic relationships.
public function comments()
{
return $this->hasMany(Comment::class, 'commentable_cuid', 'cuid');
}
$cuid = \Parables\LaravelCuid2\Facades\Cuid2::generate(['seed' => 'test']);
Auto-Increment Conflict
$table->id(); // Auto-increment primary key
$table->string('cuid')->unique()->index(); // Cuid2 column
id(), queries joining on cuid will be slower.Indexing
cuid column for performance:
$table->string('cuid')->index();
where('cuid', ...) will scan the entire table.Collision Risk
update() instead of create() for updates.Database Constraints
cuid column is unique to prevent duplicates. The package handles this by default.random_bytes() entropy source (required for Cuid2)./dev/urandom restrictions on Linux).config/cuid2.php:
'debug' => env('CUID2_DEBUG', false),
Logs will appear in storage/logs/laravel.log.Custom Entropy
Override the default entropy sources by binding a custom generator to the cuid2.entropy service provider:
$this->app->bind(\Parables\LaravelCuid2\Contracts\EntropyGenerator::class, function () {
return new CustomEntropyGenerator();
});
Event Listeners
Listen for cuid2.generated events to log or transform Cuids:
use Parables\LaravelCuid2\Events\CuidGenerated;
event(new CuidGenerated($cuid, $model));
Testing
Mock Cuids in tests using the seed option:
$cuid = \Parables\LaravelCuid2\Facades\Cuid2::generate(['seed' => 'fixed-seed']);
$this->assertEquals('cl7x89q0x000008l10000001', $cuid);
$cuids = \Parables\LaravelCuid2\Facades\Cuid2::generate(100);
How can I help you explore Laravel packages today?