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

Hashids Bundle Laravel Package

cayetanosoriano/hashids-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:

    composer require cayetanosoriano/hashids-bundle
    

    (Note: The package is outdated; prefer videlalvaro/php-hashids + manual service registration for modern Laravel.)

  2. Register the Bundle (Symfony 2.x context):

    // app/AppKernel.php
    new cayetanosoriano\HashidsBundle\cayetanosorianoHashidsBundle(),
    
  3. Configure in config.yml:

    cayetanosoriano_hashids:
        salt: "your-secret-salt"  # Required for security
        min_hash_length: 8       # Default: 8
        alphabet: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"  # Customize if needed
    
  4. First Use Case:

    // Symfony 2.x Controller
    $hashids = $this->get('hashids');
    $hash = $hashids->encode(42);  // "3k"
    $decoded = $hashids->decode($hash);  // [42]
    

Laravel Adaptation Note: Since this is a Symfony bundle, Laravel developers would:

  • Use videlalvaro/php-hashids directly (no bundle needed).
  • Register a service in config/app.php:
    'hashids' => function ($app) {
        return new \Hashids\Hashids('salt', 8, 'abcdefghijklmnopqrstuvwxyz');
    },
    
  • Inject via constructor or app('hashids').

Implementation Patterns

Core Workflows

  1. Obfuscating IDs:

    // Encode an ID (e.g., for URLs or display)
    $hash = app('hashids')->encode($userId);  // "aB3"
    
    // Decode in routes or controllers
    $userId = app('hashids')->decode($hash)[0];
    
  2. Route Integration (Symfony 2.x):

    # routing.yml
    user_show:
        path:     /user/{hash}
        defaults: { _controller: AppBundle:User:show }
        requirements:
            hash: \w+  # Regex to match hashids output
    
    // Controller
    public function showAction($hash) {
        $id = app('hashids')->decode($hash)[0];
        return $this->render(['id' => $id]);
    }
    
  3. Database-Friendly Hashing:

    • Store hashes in URLs or UI (not DB) to avoid exposing IDs.
    • Use min_hash_length to balance readability vs. collision risk.
  4. Custom Alphabets:

    • Restrict to a-z0-9 for URL safety:
      alphabet: "abcdefghijklmnopqrstuvwxyz0123456789"
      

Laravel-Specific Patterns

  • Service Provider:
    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->singleton('hashids', function () {
            return new \Hashids\Hashids(config('hashids.salt'), config('hashids.min_length'));
        });
    }
    
  • Config File (config/hashids.php):
    return [
        'salt' => env('HASHIDS_SALT', 'default-salt'),
        'min_length' => 8,
        'alphabet' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
    ];
    

Gotchas and Tips

Pitfalls

  1. No Laravel Support:

    • The bundle is Symfony 2.x only. Use videlalvaro/php-hashids for Laravel.
    • Avoid mixing Symfony bundles in Laravel (dependency conflicts).
  2. Salt Management:

    • Never hardcode salts in config. Use environment variables:
      salt: "%env(HASHIDS_SALT)%"
      
    • Reset salts if compromised (requires re-hashing all IDs).
  3. Collision Risk:

    • Short min_hash_length (e.g., 4) increases collision odds. Test with:
      $hashids->encode(range(1, 10000));  // Check for duplicates
      
  4. Decode Edge Cases:

    • decode() returns an array (even for single IDs). Always use [0]:
      $id = app('hashids')->decode($hash)[0] ?? null;
      
    • Invalid hashes return [] (not false).
  5. Performance:

    • Hashing is lightweight, but avoid encoding in loops (e.g., batch processing).

Debugging Tips

  • Validate Config:
    php artisan config:clear && php artisan cache:clear
    
  • Test Hashes:
    $hash = app('hashids')->encode(123);
    var_dump(app('hashids')->decode($hash));  // Should return [123]
    
  • Check Alphabet:
    • Ensure custom alphabets include enough characters to avoid collisions.

Extension Points

  1. Custom Hashids Class: Extend \Hashids\Hashids for project-specific logic (e.g., logging):

    class CustomHashids extends \Hashids\Hashids {
        public function encodeWithLog($number) {
            $hash = parent::encode($number);
            Log::info("Encoded $number as $hash");
            return $hash;
        }
    }
    

    Register in Laravel’s service provider.

  2. Middleware for Decoding:

    // Laravel 5.8+
    public function handle($request, Closure $next) {
        $hash = $request->route('hash');
        $request->merge(['id' => app('hashids')->decode($hash)[0]]);
        return $next($request);
    }
    
  3. Doctrine Integration (Symfony 2.x):

    • Use the included ParamConverter to auto-decode route parameters:
      # services.yml
      services:
          app.hashids.param_converter:
              class: cayetanosoriano\HashidsBundle\Doctrine\ParamConverter\HashidsParamConverter
              tags:
                  - { name: doctrine.paramconverter }
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui