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.
You can install the package via composer:
composer require tobymaxham/laravel-hashidThis package relies on
hashids/hashids, which requires either the GMP or BCMath extension. GMP is recommended for best performance and should be installed if possible.
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,
];use \TobyMaxham\HashId\Facades\IdHasher;
$hash = IdHasher::encodeId(34);
// result: h:J7dVgYxKPwyQejOMnL
$id = IdHasher::decodeId($hash);
// result: 34If you prefer to use dependency injection:
use TobyMaxham\HashID\IdHasherManager;
public function show(IdHasherManager $idHasher, $hash)
{
$id = $idHasher->decodeId($hash);
return Product::findOrFail($id);
}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;
}
}- 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.
Please see CHANGELOG for more information on what has changed recently.
If you've found a bug regarding security please mail mailto:git@maxham.de instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.