Laravel Hashids is a package that provides a simple way to encode and decode unique identifiers into short, human-readable hashes. It’s particularly useful for obscuring numeric IDs, making them less predictable and improving the overall security of your application.
Key Features
- Obfuscation: Convert numeric IDs into short, unique hashes to enhance security.
- Customizable: Allows customization of hash length and alphabet.
- Simple Integration: Easy to set up and use within your Laravel application.
Installation
To install the package, you can use Composer. Run the following command in your terminal:
1 |
composer require vinkla/hashids |
Configuration
After installing the package, you need to publish the configuration file:
1 |
php artisan vendor:publish --provider="Vinkla\Hashids\HashidsServiceProvider" |
This will create a hashids.php
configuration file in the config
directory.
Configuration Options
Open the config/hashids.php
file to configure the package. You can set options like the salt, length, and alphabet for the hashes:
1 2 3 4 5 6 7 |
return [ 'default' => [ 'salt' => env('HASHIDS_SALT', 'your-salt-here'), 'length' => 8, // The length of the generated hashes 'alphabet' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', // Custom alphabet ], ]; |
Usage
1. Encoding IDs
To encode an ID, you can use the Hashids
facade. Here’s an example:
1 2 3 4 5 |
use Hashids\Hashids; $hashids = new Hashids('your-salt-here'); $encoded = $hashids->encode(123); // Encode the ID 123 echo $encoded; // Example output: '5e8c9e' |
2. Decoding Hashes
To decode a hash back into the original ID:
1 2 |
$decoded = $hashids->decode($encoded); echo $decoded[0]; // Output: 123 |
Note: The decode
method returns an array of IDs. If the hash does not match any ID, it will return an empty array.
3. Using Hashids in Models
You can easily integrate Hashids into your models. For instance, if you want to automatically encode and decode the id
attribute in a User model, you can do the following:
- Add the Hashids Trait:
Install the trait by adding it to your model:
php
1234567891011121314151617use Vinkla\Hashids\Facades\Hashids;class User extends Model{// Other model methods and propertiespublic function getRouteKey(){return Hashids::encode($this->id);}public static function findByHash($hash){$decoded = Hashids::decode($hash);return static::find($decoded[0] ?? null);}} - Using the Model with Routes:
You can define routes that use the encoded IDs:
php
1234Route::get('user/{hash}', function ($hash) {$user = User::findByHash($hash);// Handle user...});
Conclusion
Laravel Hashids provides a straightforward way to generate short, unique hashes for your IDs, helping to obscure sensitive information and improve the user experience. Its simple setup and ease of use make it a valuable addition to any Laravel application.