Looking to hire Laravel developers? Try LaraJobs

laravel-hashable-routes maintained by iridiumintel

Description
A Laravel package that provides short, secure, and per-model configurable hashed route keys instead of incremental IDs.
Last update
2025/09/27 16:49 (dev-master)
License
Links
Downloads
20

Comments
comments powered by Disqus

Laravel Hashable Routes

Latest Version on Packagist Total Downloads

A Laravel package that replaces incremental IDs with short, secure, and per-model configurable hash IDs.
Built on top of hashids/hashids.


🚀 Features

  • Generate short, obfuscated IDs for your models (abc123 instead of 42).
  • Per-model configuration (custom salt & length).
  • Optional automatic route key override (so /users/abc123 instead of /users/42).
  • Helpers: encodeId(), decodeHash(), findByHashOrNull().
  • Artisan commands for direct encode/decode in terminal.
  • Plug-and-play with Laravel (composer require).

📦 Installation

composer require iridiumintel/laravel-hashable-routes

Publish the config file:

php artisan vendor:publish --tag=config

⚙️ Configuration

config/hashable.php

return [
    'default' => [
        'salt' => env('HASHABLE_SALT', env('APP_KEY')),
        'length' => env('HASHABLE_LENGTH', 10),
        'override_route_key' => env('HASHABLE_ROUTE_KEY', true),
        'strict_binding' => env('HASHABLE_STRICT', true),
    ],

    'models' => [
        // Example: per-model override
        App\Models\User::class => [
            'salt' => env('HASHABLE_USER_SALT', env('APP_KEY')),
            'length' => 8,
            'override_route_key' => true,
            'strict_binding' => true,
        ],
    ],
];

🔑 Usage

Add the trait to your Eloquent model:

use IridiumIntel\Hashable\Hashable;

class User extends Model
{
    use Hashable;
}

Now:

$user = User::find(42);

echo $user->hash_id; 
// e.g. "gB9xL0Qjz"

$found = User::findByHash("gB9xL0Qjz");
// returns the same user

$maybe = User::findByHashOrNull("invalid");
// returns null instead of throwing

Route binding

If override_route_key is enabled (default):

Route::get('/users/{user}', fn(User $user) => $user);

// /users/gB9xL0Qjz → User#42

If disabled, routes continue using the standard id, but you can still use findByHash() manually.


🧪 Artisan Commands

Encode an ID:

php artisan hashable:encode "App\Models\User" 42
# Output: Hash for App\Models\User #42: gB9xL0Qjz

Decode a hash:

php artisan hashable:decode "App\Models\User" gB9xL0Qjz
# Output: Decoded ID for App\Models\User (gB9xL0Qjz): 42

📜 License

The MIT License (MIT).
See LICENSE for details.