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

veelasky/laravel-hashid

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require veelasky/laravel-hashid
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Veelasky\HashId\HashIdServiceProvider" --tag="hashid-config"
    
  2. Enable for a Model: Add the HasHashId trait to your Eloquent model:

    use Veelasky\HashId\HasHashId;
    
    class User extends Model
    {
        use HasHashId;
    }
    
  3. First Use Case: Access the hashed ID via $model->hashId or $model->getHashId(). Retrieve the original ID from a hash:

    $user = User::where('hash_id', 'abc123')->first();
    $originalId = $user->id; // Original ID
    

Key Configurations

  • Check config/hashid.php for default settings (e.g., alphabet, min_length, salt).
  • Customize per-model by overriding $hashIdConfig in the model:
    protected $hashIdConfig = [
        'alphabet' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
        'min_length' => 10,
    ];
    

Implementation Patterns

Common Workflows

  1. Generating Hashes:

    • Automatically generated on save()/create() if $hashId is empty.
    • Manually trigger with:
      $model->generateHashId();
      
  2. Querying by Hash:

    • Use hash_id in queries:
      User::where('hash_id', 'abc123')->get();
      
    • Scope for convenience:
      User::byHashId('abc123')->first();
      
  3. URL-Friendly IDs:

    • Useful for RESTful APIs or shareable links:
      route('users.show', ['user' => $user->hashId]); // /users/abc123
      
  4. Migrations:

    • Add hash_id column to your table:
      Schema::table('users', function (Blueprint $table) {
          $table->string('hash_id')->unique()->nullable();
      });
      
  5. API Responses:

    • Serialize hashed IDs in JSON responses:
      return User::find($id)->append('hash_id');
      

Integration Tips

  • APIs: Use hash_id in API responses to hide internal IDs.
  • Frontend: Pass hash_id in URLs or forms for user-friendly interactions.
  • Caching: Cache models by hash_id for faster lookups:
    Cache::remember("user:{$hashId}", now()->addHours(1), fn() => User::byHashId($hashId)->first());
    
  • Validation: Validate hash_id format in forms:
    $request->validate(['hash_id' => 'required|string|hashid']);
    

Gotchas and Tips

Pitfalls

  1. Collision Risk:

    • HashIds are not cryptographically secure. Use them for display/URLs, not security-sensitive data.
    • Monitor for collisions in production (unlikely but possible with short lengths).
  2. Performance:

    • Hash generation is lightweight, but avoid generating hashes in bulk operations (e.g., Model::all()). Use ->pluck('hash_id') instead.
  3. Database Indexing:

    • Ensure hash_id is indexed for query performance:
      Schema::table('users', function (Blueprint $table) {
          $table->string('hash_id')->unique()->index();
      });
      
  4. Salt Management:

    • If using a salt, ensure it’s consistent across environments (configured in .env or config/hashid.php).
    • Changing the salt will invalidate all existing hashes.
  5. Model Events:

    • Hashes are generated on creating and updating events. Override these if custom logic is needed:
      protected static function boot()
      {
          parent::boot();
          static::creating(function ($model) {
              if (!$model->hash_id) {
                  $model->generateHashId();
              }
          });
      }
      

Debugging

  • Invalid Hashes: Use HashId::decode($hash) to check if a hash is valid:
    if (!HashId::decode($hash)) {
        abort(404, 'Invalid hash ID');
    }
    
  • Logging: Enable debug mode in config/hashid.php to log hash generation:
    'debug' => env('HASHID_DEBUG', false),
    

Extension Points

  1. Custom Alphabets:

    • Override the default alphabet for specific models:
      protected $hashIdConfig = [
          'alphabet' => 'custom-alphabet-here',
      ];
      
  2. Hash Length:

    • Adjust min_length to balance readability and collision risk (default: 8).
  3. Custom Storage:

    • Store hashes in a separate table or cache layer if needed (extend the trait or use model observers).
  4. Testing:

    • Mock HashId in tests to avoid flakiness:
      HashId::shouldReceive('encode')->andReturn('test123');
      
  5. Fallbacks:

    • Handle cases where hash_id might be missing (e.g., legacy data):
      $id = $model->hash_id ?? $model->id;
      
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle