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

parables/laravel-cuid2

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require parables/laravel-cuid2
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Parables\LaravelCuid2\LaravelCuid2ServiceProvider" --tag="config"
    
  2. 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.

  3. Key Config Check config/cuid2.php for:

    • column_name (default: cuid)
    • generate_on_create (default: true)
    • generate_on_update (default: false)

Implementation Patterns

Core Workflows

  1. Basic Usage

    $post = Post::create(['title' => 'Hello World']);
    // $post->cuid is now a Cuid2 string (e.g., "cl7x89q0x000008l10000001")
    
  2. Manual Generation

    $cuid = \Parables\LaravelCuid2\Facades\Cuid2::generate();
    $post = Post::create(['title' => 'Manual Cuid', 'cuid' => $cuid]);
    
  3. Querying by Cuid

    $post = Post::where('cuid', 'cl7x89q0x000008l10000001')->first();
    // Add index to `cuid` column in your migration for performance:
    $table->string('cuid')->unique()->index();
    
  4. Custom Column Names

    class Post extends Model
    {
        use HasCuid2;
    
        protected $cuidColumn = 'custom_id';
    }
    

Integration Tips

  • API Responses: Serialize cuid in JSON responses for client-side use.
    $post->append('cuid'); // Ensure it's included in `toArray()`.
    
  • Relationships: Use cuid as a foreign key in polymorphic relationships.
    public function comments()
    {
        return $this->hasMany(Comment::class, 'commentable_cuid', 'cuid');
    }
    
  • Seeding: Generate Cuids deterministically for testing.
    $cuid = \Parables\LaravelCuid2\Facades\Cuid2::generate(['seed' => 'test']);
    

Gotchas and Tips

Pitfalls

  1. Auto-Increment Conflict

    • The package does not disable auto-increment by default. Ensure your migration includes both:
      $table->id(); // Auto-increment primary key
      $table->string('cuid')->unique()->index(); // Cuid2 column
      
    • If you remove id(), queries joining on cuid will be slower.
  2. Indexing

    • Always index the cuid column for performance:
      $table->string('cuid')->index();
      
    • Without indexing, queries like where('cuid', ...) will scan the entire table.
  3. Collision Risk

    • While collisions are astronomically unlikely, avoid regenerating Cuids for existing records. Use update() instead of create() for updates.
  4. Database Constraints

    • Ensure the cuid column is unique to prevent duplicates. The package handles this by default.

Debugging

  • Validation Errors: If Cuids fail to generate, check:
    • PHP’s random_bytes() entropy source (required for Cuid2).
    • Server misconfigurations (e.g., /dev/urandom restrictions on Linux).
  • Log Generation: Enable debug mode in config/cuid2.php:
    'debug' => env('CUID2_DEBUG', false),
    
    Logs will appear in storage/logs/laravel.log.

Extension Points

  1. 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();
    });
    
  2. Event Listeners Listen for cuid2.generated events to log or transform Cuids:

    use Parables\LaravelCuid2\Events\CuidGenerated;
    
    event(new CuidGenerated($cuid, $model));
    
  3. Testing Mock Cuids in tests using the seed option:

    $cuid = \Parables\LaravelCuid2\Facades\Cuid2::generate(['seed' => 'fixed-seed']);
    $this->assertEquals('cl7x89q0x000008l10000001', $cuid);
    

Performance Tips

  • Batch Generation: Generate Cuids in bulk for seeding:
    $cuids = \Parables\LaravelCuid2\Facades\Cuid2::generate(100);
    
  • Caching: Cache generated Cuids if your app has low entropy requirements (e.g., for non-critical IDs).
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours