On-the-Fly Hashids with the Eloquent Hashids Package

News

August 19th, 2019

eloquent-hashids-featured.png

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:

1use Illuminate\Database\Eloquent\Model;
2use Mtvs\EloquentHashids\HasHashid;
3use Mtvs\EloquentHashids\HashidRouting;
4 
5class Item extends Model
6{
7 use HasHashid, HashidRouting;
8}

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

1// Generating the model hashid based on its key
2$item->hashid();
3 
4// Finding a model based on the provided hashid or
5// returning null on failure
6Item::findByHashid($hashid);
7 
8// Finding a model based on the provided hashid or
9// throwing a ModelNotFoundException on failure
10Item::findByHashidOrFail($hashid);
11 
12// Decoding a hashid to the integer id
13$item->hashidToId($hashid);
14 
15// Getting the name of the hashid connection
16$item->getHashidsConnection();

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.