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 the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Full Stack or Back-End Developer
Alexandria, VA; Tallahassee, FL; Orlando, FL
Marketing for Change
Full Stack Software Engineer
Atlanta, GA or Remote
Laravel/PHP Developer
Chicago, IL
Neon One
Software Engineer, Web Applications
Vaughan, ON, Canada
Blast Motion
Contract Services Software Engineer (Laravel | Vue | Tailwind)
Riverbed Technology
Senior Laravel Developer
Wilmington, NC
GE Software Inc.
Senior Full Stack Developer (PHP | Vue | DDD)
Charleston, SC