Laravel Hashids – Generate short unique hashes

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:

bash
 

Configuration

After installing the package, you need to publish the configuration file:

bash

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:

php
 

Usage

1. Encoding IDs

To encode an ID, you can use the Hashids facade. Here’s an example:

php

2. Decoding Hashes

To decode a hash back into the original ID:

php

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:

  1. Add the Hashids Trait:

    Install the trait by adding it to your model:

    php
  2. Using the Model with Routes:

    You can define routes that use the encoded IDs:

    php
     

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top