PHPackages                             mcandylab/laravel-cuid2 - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. mcandylab/laravel-cuid2

ActiveLibrary

mcandylab/laravel-cuid2
=======================

CUID2 support for Laravel

v3.0.1(4w ago)3185MITPHPPHP ^8.2CI passing

Since Jul 12Pushed 1mo agoCompare

[ Source](https://github.com/mcandylab/laravel-cuid2)[ Packagist](https://packagist.org/packages/mcandylab/laravel-cuid2)[ Docs](https://github.com/mcandylab/laravel-cuid2)[ RSS](/packages/mcandylab-laravel-cuid2/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (9)Versions (7)Used By (0)

Laravel CUID2
=============

[](#laravel-cuid2)

[🇬🇧 **English**](README.md) | [🇷🇺 Русский](README.ru.md)

[![Latest Version on Packagist](https://camo.githubusercontent.com/700efcefb267a98599161a624e308f1183e68ca879eddf4e7737a1ce295299e0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d63616e64796c61622f6c61726176656c2d63756964322e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mcandylab/laravel-cuid2)[![Total Downloads](https://camo.githubusercontent.com/14d43f4bb04d3f02cb8e131c336f3aac3c9e37ae98354d65c4ce5a4b05eae430/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d63616e64796c61622f6c61726176656c2d63756964322e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mcandylab/laravel-cuid2)[![run-tests](https://github.com/mcandylab/laravel-cuid2/actions/workflows/main.yml/badge.svg)](https://github.com/mcandylab/laravel-cuid2/actions/workflows/main.yml)

Use [CUID2](https://github.com/paralleldrive/cuid2) as primary keys for your Eloquent models in Laravel. The package provides a model trait, a global `cuid2()` helper and schema macros for migrations. Generation is delegated to the [`visus/cuid2`](https://github.com/visus-io/php-cuid2) library.

Requirements
------------

[](#requirements)

- PHP &gt;= 8.2
- Laravel 12 or 13 (Laravel 13 requires PHP 8.3+)

Installation
------------

[](#installation)

```
composer require mcandylab/laravel-cuid2
```

The package uses auto-discovery. Publish the config if needed:

```
php artisan vendor:publish --provider="Mcandylab\LaravelCuid2\LaravelCuid2ServiceProvider" --tag="config"
```

Usage
-----

[](#usage)

### Model trait

[](#model-trait)

Add the `HasCuid2` trait — the primary key will be automatically populated with a valid CUID2 when a record is created:

```
use Illuminate\Database\Eloquent\Model;
use Mcandylab\LaravelCuid2\Concerns\HasCuid2;

class Post extends Model
{
    use HasCuid2;
}
```

The trait sets `keyType = 'string'` and `incrementing = false` for you. To generate a cuid2 for more than just the primary key, override `uniqueIds()`:

```
public function uniqueIds(): array
{
    return [$this->getKeyName(), 'public_id'];
}
```

### Migrations

[](#migrations)

The `cuid2()` and `foreignCuid2()` macros declare `varchar` columns (Laravel's `Schema::defaultStringLength`, 255 by default). They are fully indexable across databases and fit any value the package generates, including prefixed `{prefix}_{cuid2}` identifiers:

```
Schema::create('posts', function (Blueprint $table) {
    $table->cuid2()->primary();      // id column
    $table->string('title');
    $table->timestamps();
});

Schema::create('comments', function (Blueprint $table) {
    $table->cuid2()->primary();
    $table->foreignCuid2('post_id')->constrained();
    $table->text('body');
});
```

For polymorphic relations use `cuid2Morphs()` (and `nullableCuid2Morphs()`), the CUID2 counterparts of Laravel's `ulidMorphs()`. They add a `{name}_type`string column, a `{name}_id` varchar column and a composite index:

```
Schema::create('tokens', function (Blueprint $table) {
    $table->cuid2()->primary();
    $table->cuid2Morphs('tokenable');          // tokenable_type + tokenable_id
    $table->string('token');
});

// nullable variant
$table->nullableCuid2Morphs('tokenable');
```

### Helper

[](#helper)

```
$id = cuid2();      // 24 characters (or config('laravel-cuid2.length'))
$short = cuid2(10); // exactly 10 characters (4..32 allowed)
```

### Facade

[](#facade)

```
use Mcandylab\LaravelCuid2\LaravelCuid2Facade as Cuid2;

Cuid2::generate();          // generate an id
Cuid2::isValid($someId);    // validate a string
```

### Str macros

[](#str-macros)

Aligned with the core `Str::uuid()` / `Str::ulid()` helpers:

```
use Illuminate\Support\Str;

Str::cuid2();          // generate (respects config('laravel-cuid2.length'))
Str::cuid2(10);        // exactly 10 characters (4..32 allowed)
Str::isCuid2($value);  // validate a value (false for non-strings)
```

### Faker

[](#faker)

A `cuid2()` Faker formatter is available for factories and seeders:

```
use App\Models\Post;

Post::factory()->create(['id' => fake()->cuid2()]);

fake()->cuid2();   // generate (respects config('laravel-cuid2.length'))
fake()->cuid2(10); // exactly 10 characters (4..32 allowed)
```

### Validation

[](#validation)

The `cuid2` rule validates that a value is a well-formed CUID2 of any valid length (4..32). It is available in three forms:

```
use Illuminate\Validation\Rule;
use Mcandylab\LaravelCuid2\Rules\Cuid2;

$request->validate([
    'id'    => 'cuid2',          // string rule
    'ref'   => [new Cuid2],      // rule object
    'ext'   => [Rule::cuid2()],  // rule macro
]);
```

### Prefixed identifiers (Stripe-style)

[](#prefixed-identifiers-stripe-style)

You can produce human-readable identifiers such as `user_p6p168tx…` by declaring a `$cuid2Prefix` property on the model. The prefix is just an envelope — the cuid2 part after the `_` stays fully spec-compliant:

```
class User extends Model
{
    use HasCuid2;

    protected string $cuid2Prefix = 'user';
}
```

No special column type is needed: `cuid2()` and `foreignCuid2()` already create a `varchar` that fits any `{prefix}_{cuid2}` value:

```
Schema::create('users', function (Blueprint $table) {
    $table->cuid2()->primary();
    $table->string('name');
});

// a foreign key referencing a prefixed model
$table->foreignCuid2('user_id');
```

The generators accept an optional prefix too:

```
cuid2(prefix: 'user');            // user_…
Str::cuid2(prefix: 'user');       // user_…
fake()->cuid2(prefix: 'user');    // user_…
```

Validation can optionally check the prefix — it verifies the `{prefix}_` and that the remainder is a valid CUID2. Without a prefix the rule is unchanged:

```
$request->validate([
    'id'  => 'cuid2:user',                 // string rule
    'id2' => [new Cuid2('user')],          // rule object
    'id3' => [Rule::cuid2(prefix: 'user')], // rule macro
]);

Str::isCuid2($value, 'user');              // and via the Str macro
```

> **Note:** `cuid2Morphs()` / `nullableCuid2Morphs()` take no prefix argument — a polymorphic column may point at models with different prefixes, and the prefix is already implied by the `{name}_type` column. Like every id column in this package, `{name}_id` is a `varchar`, so a prefixed model can safely be a polymorphic target without truncation.

Configuration
-------------

[](#configuration)

`config/laravel-cuid2.php`:

```
return [
    // Identifier length (4..32). The cuid2 standard is 24.
    'length' => (int) env('CUID2_LENGTH', 24),
];
```

`length` only affects generation (`cuid2()`, `Str::cuid2()`, `fake()->cuid2()`, `HasCuid2`). Schema macros are unaffected — they always declare a `varchar`, so changing the length does not require a migration.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

See [CHANGELOG](CHANGELOG.md).

Contributing
------------

[](#contributing)

See [CONTRIBUTING](CONTRIBUTING.md).

Security
--------

[](#security)

If you discover any security related issues, please [open an issue](https://github.com/mcandylab/laravel-cuid2/issues).

Credits
-------

[](#credits)

- [Andrey Abramov](https://github.com/mcandylab)
- [All Contributors](../../contributors)
- [visus-io/php-cuid2](https://github.com/visus-io/php-cuid2)

License
-------

[](#license)

The MIT License (MIT). See [License File](LICENSE.md).

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance92

Actively maintained with recent releases

Popularity19

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~5 days

Total

5

Last Release

29d ago

Major Versions

v1.2.0 → v2.0.02026-07-17

v2.0.0 → v3.0.02026-07-19

### Community

Maintainers

![](https://www.gravatar.com/avatar/63a90db093eb3bb95572c96a227061b980c8eeccd593807edbc4fdb1ec7bebf5?d=identicon)[mcandylab](/maintainers/mcandylab)

---

Top Contributors

[![mcandylab](https://avatars.githubusercontent.com/u/20170366?v=4)](https://github.com/mcandylab "mcandylab (9 commits)")

---

Tags

mcandylablaravel-cuid2

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mcandylab-laravel-cuid2/health.svg)

```
[![Health](https://phpackages.com/badges/mcandylab-laravel-cuid2/health.svg)](https://phpackages.com/packages/mcandylab-laravel-cuid2)
```

###  Alternatives

[craftcms/cms

Craft CMS

3.6k3.7M3.5k](/packages/craftcms-cms)[laravel/ai

The official AI SDK for Laravel.

1.1k6.4M360](/packages/laravel-ai)[psalm/plugin-laravel

Psalm plugin for Laravel

3365.5M359](/packages/psalm-plugin-laravel)[ublabs/blade-simple-icons

A package to easily make use of Simple Icons in your Laravel Blade views.

1868.9k](/packages/ublabs-blade-simple-icons)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
