On-the-Fly Hashids with the Eloquent Hashids Package

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: News


Join 31,000+ others and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior Fullstack Developer / Architect (w/m/d)
Remote / Munich - Germany
envivo.select GmbH
Medior full stack developer (Laravel)
Deventer (or remote) in the Netherlands, Dutch speaking required.
Senior Full Stack PHP Developer (Laravel)
Senior Laravel Developer
Senior Full-Stack Engineer