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

Hash Model Ids Laravel Package

netsells/hash-model-ids

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require netsells/hash-model-ids
    php artisan vendor:publish --tag=hash-model-ids-config
    

    Add HASH_MODEL_IDS_SALT to .env (e.g., HASH_MODEL_IDS_SALT=your_unique_salt_here).

  2. Apply Trait: Use the HashesModelIdsTrait in your Eloquent model:

    use Netsells\HashModelIds\HashesModelIdsTrait;
    
    class User extends Model
    {
        use HashesModelIdsTrait;
    }
    
  3. First Use Case: Access the hashed ID directly:

    $user = User::find(1);
    echo $user->hashed_id; // e.g., "abc123xyz"
    

Implementation Patterns

Core Workflows

  1. Querying by Hashed IDs:

    // Single hashed ID
    $user = User::whereHashedId($hashedId)->first();
    
    // Multiple hashed IDs
    $users = User::whereHashedIds([$hashedId1, $hashedId2])->get();
    
  2. Route Binding: Define routes using hashed IDs for implicit binding:

    Route::get('/users/{user}', [UserController::class, 'show']);
    

    Access via URL:

    $url = route('users.show', ['user' => $user->hashed_id]);
    
  3. Form Validation: Validate hashed IDs in requests:

    use Netsells\HashModelIds\Rules\ExistsWithHashedIdRule;
    
    public function rules()
    {
        return [
            'hashed_id' => [
                new ExistsWithHashedIdRule(User::class)
                    ->where('active', true),
            ],
        ];
    }
    
  4. Custom Scopes: Extend the trait for custom logic:

    class User extends Model
    {
        use HashesModelIdsTrait;
    
        public function scopeActive($query)
        {
            return $query->where('active', true);
        }
    }
    

Integration Tips

  • APIs: Use hashed IDs in API responses to hide internal IDs.
  • URLs: Generate shareable URLs with hashed IDs (e.g., /profile/{hashed_id}).
  • Caching: Cache hashed IDs for performance (e.g., Cache::remember()).
  • Testing: Mock hashed IDs in tests:
    $this->app->instance('hash.model_ids.salt', 'test_salt');
    

Gotchas and Tips

Pitfalls

  1. Salt Management:

    • Never commit the HASH_MODEL_IDS_SALT to version control. Use .env.
    • If the salt changes, all hashed IDs become invalid. Document salt changes carefully.
  2. Route Binding Conflicts:

    • Ensure route model binding keys match the trait’s getRouteKeyName() (default: hashed_id).
    • Override getRouteKey() if needed:
      public function getRouteKey()
      {
          return $this->hashed_id;
      }
      
  3. Performance:

    • Hashed ID lookups add a query. Avoid deep nesting in queries (e.g., whereHas with hashed IDs).
    • Index the hashed_id column in your database for faster lookups:
      Schema::table('users', function (Blueprint $table) {
          $table->string('hashed_id')->unique();
      });
      
  4. Collision Risk:

    • Hash collisions are theoretically possible but unlikely with a strong salt. Monitor for duplicates in production.

Debugging

  • Invalid Hashed IDs:

    • Use HashModelIds::generateHash($id) to verify hash generation.
    • Check for typos in the salt or hashed ID format.
  • Route Binding Failures:

    • Ensure the hashed_id column exists and is populated. Debug with:
      dd($user->hashed_id, $user->getRouteKey());
      

Extension Points

  1. Custom Hashing: Override the hash generation logic:

    use Netsells\HashModelIds\HashModelIds;
    
    class CustomUser extends Model
    {
        use HashesModelIdsTrait;
    
        protected function getHashedIdAttribute($value)
        {
            return HashModelIds::generateHash($this->id, 'custom_salt');
        }
    }
    
  2. Additional Query Methods: Extend the trait to add custom scopes:

    public function scopeWhereHashedIdLike($query, $search)
    {
        return $query->where('hashed_id', 'like', "%{$search}%");
    }
    
  3. Middleware: Validate hashed IDs in middleware:

    public function handle($request, Closure $next)
    {
        if ($request->hashed_id) {
            $model = Model::whereHashedId($request->hashed_id)->firstOrFail();
        }
        return $next($request);
    }
    
  4. Database Events: Listen for model events to regenerate hashed IDs:

    Model::created(function ($model) {
        $model->forceFill(['hashed_id' => HashModelIds::generateHash($model->id)])->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.
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
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope