tobymaxham / laravel-hashid
This package enables support for hashed ID's in your laravel application.
Requires
- php: ^8.2
- hashids/hashids: ^4.1
- illuminate/database: ^10.0|^11.0
- illuminate/support: ^10.0|^11.0
Requires (Dev)
- laravel/pint: ^1.21
This package is auto-updated.
Last update: 2025-02-21 23:41:19 UTC
README
This Laravel package ensures that IDs are not directly visible in URLs or other public areas.
Instead, they are encoded and, for example, products/34
is converted to products/h:J7dVgYxKPwyQejOMnL
.
Installation
You can install the package via composer:
composer require tobymaxham/laravel-hashid
Configuration
Publish the configuration file with:
php artisan vendor:publish --provider="TobyMaxham\HashID\IdHasherServiceProvider"
For example, the configuration file config/hashids.php
looks like this:
return [ 'prefix' => env('HASH_PREFIX', 'h:'), 'salt' => env('HASH_SALT', 'your-salt-string'), 'length' => env('HASH_LENGTH', 18), 'alphabet' => env('HASH_ALPHABET', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'), 'exception' => \TobyMaxham\HashId\Exceptions\WrongIdException::class, 'exception_message' => 'WrongIdException', 'disable_exception' => false, ];
Usage
Using the Facade
use \TobyMaxham\HashId\Facades\IdHasher; $hash = IdHasher::encodeId(34); // result: h:J7dVgYxKPwyQejOMnL $id = IdHasher::decodeId($hash); // result: 34
Using Dependency Injection
If you prefer to use dependency injection:
use TobyMaxham\HashID\IdHasherManager; public function show(IdHasherManager $idHasher, $hash) { $id = $idHasher->decodeId($hash); return Product::findOrFail($id); }
Automatically Decode Hash IDs
You can use the trait HashId
in your models to automatically decode hash IDs:
class Product extends Model { use Hasher; }
Now you can use them in routes:
// web.php Route::get('products/{product}', 'ProductController@show'); // ProductController.php class ProductController extends Controller { public function show(Product $product) { return $product; } }
Security
- Make sure your salt value remains secret and is not published in your repository.
- The encoded IDs are not encrypted, just encoded. Therefore, they are not secure and should not be used for security purposes.
Changelog
Please see CHANGELOG for more information on what has changed recently.
Security Vulnerabilities
If you've found a bug regarding security please mail git@maxham.de instead of using the issue tracker.
Support me
Credits
License
The MIT License (MIT). Please see License File for more information.