On-the-Fly Hashids with the Eloquent Hashids Package


August 19th, 2019

On-the-Fly Hashids with the Eloquent Hashids Package

Eloquent Hashids is a package by Mohammad Ali Tavassoli that give you on-the-fly hashids for Laravel Eloquent models:

This [package] adds hashids to Laravel Eloquent models by encoding/decoding them on the fly rather than persisting them in the database. So no need for another database column and also higher performance by using primary keys in queries.

According to the README this package’s main features include:

  • Generating hashids for models
  • Resolving hashids to models
  • Ability to customize hashid settings for each model
  • Route binding with hashids (optional)

Here’s an example model which uses the provided traits for the hashid and route binding features:

use Illuminate\Database\Eloquent\Model;
use Mtvs\EloquentHashids\HasHashid;
use Mtvs\EloquentHashids\HashidRouting;
class Item extends Model
use HasHashid, HashidRouting;

Here is the basic API using this package with your models:

// Generating the model hashid based on its key
// Finding a model based on the provided hashid or
// returning null on failure
// Finding a model based on the provided hashid or
// throwing a ModelNotFoundException on failure
// Decoding a hashid to the integer id
// Getting the name of the hashid connection

You can learn more about this package, get full installation instructions, and view the source code on GitHub at mtvs/eloquent-hashids.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.