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

deligoez/laravel-model-hashid

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require deligoez/laravel-model-hashid
    

    Publish the config file:

    php artisan vendor:publish --provider="Deligoez\LaravelModelHashid\HashidServiceProvider"
    
  2. Configure Models: Add the Hashid trait to your Eloquent model:

    use Deligoez\LaravelModelHashid\Hashid;
    
    class User extends Model
    {
        use Hashid;
    }
    
  3. First Use Case: Generate a hash ID for a new model instance:

    $user = new User();
    $user->hashid = $user->generateHashid(); // e.g., "abc123"
    $user->save();
    
  4. Retrieve by Hash ID:

    $user = User::findByHashid('abc123');
    

Implementation Patterns

Core Workflows

  1. Automatic Hash ID Generation: Use the Hashid trait with autoGenerateHashid in config:

    // config/hashid.php
    'autoGenerateHashid' => true,
    

    Now, every new model instance will auto-generate a hash ID on save.

  2. Custom Hash ID Fields: Override the default hashid field name:

    class User extends Model
    {
        use Hashid;
    
        protected $hashidField = 'custom_hash';
    }
    
  3. Route Model Binding: Bind routes to hash IDs in routes/web.php:

    Route::get('/users/{user:hashid}', [UserController::class, 'show']);
    
  4. Query Scoping: Filter models by hash ID:

    $users = User::whereHashid('abc123')->get();
    

Integration Tips

  • APIs: Return hash IDs in JSON responses instead of auto-increment IDs.
  • URLs: Use hash IDs in shareable links (e.g., /posts/{post:hashid}).
  • Migrations: Add the hash ID column to your database table:
    Schema::table('users', function (Blueprint $table) {
        $table->string('hashid')->unique()->nullable();
    });
    

Gotchas and Tips

Pitfalls

  1. Collision Risk: Hash IDs are not cryptographically secure. Use them for display purposes only, not sensitive data. For uniqueness, ensure your underlying ID (e.g., id) is unique.

  2. Performance: Hash ID generation is lightweight, but avoid generating them in bulk (e.g., for 10,000+ records at once). Use transactions or batch processing.

  3. Database Indexing: Ensure the hashid column is indexed for faster lookups:

    Schema::table('users', function (Blueprint $table) {
        $table->string('hashid')->unique()->index();
    });
    
  4. Route Binding Conflicts: If using ImplicitModelBinding, ensure the hashid field is not ambiguous with other route parameters. Use explicit binding:

    Route::bind('user', function ($value) {
        return User::whereHashid($value)->firstOrFail();
    });
    

Debugging

  • Invalid Hash IDs: If findByHashid() returns null, verify:

    • The hash ID exists in the database.
    • The hashidField config matches the column name.
    • The underlying id hasn’t been deleted (hash IDs are tied to the original ID).
  • Config Overrides: Temporarily disable auto-generation to debug:

    'autoGenerateHashid' => false,
    

Extension Points

  1. Custom Hash ID Format: Override the generateHashid() method to use a custom Hashids instance:

    use Hashids\Hashids;
    
    class User extends Model
    {
        use Hashid;
    
        public function generateHashid()
        {
            $hashids = new Hashids('custom_salt', 8, 'abcdefghijklmnopqrstuvwxyz');
            return $hashids->encode($this->getKey());
        }
    }
    
  2. Soft Deletes: If using SoftDeletes, ensure findByHashid() respects soft-deleted models:

    // In HashidServiceProvider
    public function boot()
    {
        Model::shouldBeStrictlyAvailable();
        Model::resolving(function ($model) {
            if (method_exists($model, 'findByHashid')) {
                $model->setAttribute('hashid', $model->generateHashid());
            }
        });
    }
    
  3. Testing: Mock hash ID generation in tests:

    $user = User::factory()->make();
    $user->hashid = 'test123';
    $user->save();
    
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.
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
atriumphp/atrium