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

Nanoid Php Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. 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.

  2. 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"
    
  3. Where to Look First

    • NanoId PHP 2.0 Docs (check for updated examples)
    • src/NanoId.php for core logic (verify PHP 8.2+ compatibility)
    • tests/ for edge cases and PHP 8.2/8.3-specific tests

Implementation Patterns

Core Workflows

  1. Basic ID Generation (PHP 8.2+)

    $nanoId = new NanoId(); // Default: 21 chars, alphanumeric + '-'
    $id = $nanoId->generate();
    
  2. Custom Length & Alphabet (PHP 8.2+)

    $customId = new NanoId(10, NanoId::ALPHABET_NO_DASH);
    $id = $customId->generate();
    
  3. 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();
            });
        }
    }
    
  4. URL-Safe Slugs (PHP 8.2+)

    $slugId = new NanoId(8, NanoId::ALPHABET_LOWER);
    $slug = $slugId->generate(); // e.g., "aBc123xy"
    
  5. Batch Generation (PHP 8.2+)

    $batch = new NanoId();
    $ids = array_map(fn() => $batch->generate(), range(1, 100));
    

Laravel-Specific Patterns

  1. 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);
        });
    }
    
  2. Request-Based IDs (Laravel 9+)

    // app/Http/Controllers/PostController.php
    public function store(Request $request) {
        $nanoId = new NanoId(12);
        $request->merge(['uuid' => $nanoId->generate()]);
    }
    
  3. 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();
    });
    
  4. API Response IDs (PHP 8.2+)

    return response()->json([
        'data' => [
            'id' => $nanoId->generate(),
            'title' => 'Example Post',
        ]
    ]);
    

Gotchas and Tips

Pitfalls

  1. PHP Version Drop (Breaking Change)

    • Issue: Version 2.0 drops support for PHP < 7.1.
    • Fix: Update Laravel project to PHP 7.1+ (recommended: PHP 8.2+ for full compatibility).
    • Workaround: Stick with 1.x branch if using PHP < 7.1.
  2. Collision Risk (Unchanged)

    • NanoIDs are not cryptographically secure. Use longer lengths (e.g., 21 chars) for critical systems.
    • Test collision probability with:
      $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);
      
  3. 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);
      
  4. Database Indexing (Unchanged)

    • NanoIDs are longer than UUIDs (21 chars vs. 36). Ensure your database column type supports this (e.g., VARCHAR(255)).
    • Avoid indexing if uniqueness isn’t critical.
  5. PHP 8.4 Deprecation Warnings (Fixed in 2.0)

    • Issue: Previous versions threw warnings in PHP 8.4.
    • Fix: Upgrade to 2.0 for full PHP 8.4 compatibility.

Debugging Tips

  1. 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));
    
  2. 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
    
  3. 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
    

Extension Points

  1. Custom ID Formats (PHP 8.2+) Extend NanoId to support formats like:

    class CustomNanoId extends NanoId {
        public function generateWithPrefix() {
            return 'ID-' . parent::generate();
        }
    }
    
  2. 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();
    });
    
  3. Integration with Laravel Scout (PHP 8.2+) Use NanoIDs as searchable keys:

    Scout::model('Post')->searchableAs('uuid');
    
  4. 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),
    ];
    
  5. 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();
    });
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor