On-the-Fly Hashids with the Eloquent Hashids Package
Published on by Paul Redmond
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$item->hashid(); // Finding a model based on the provided hashid or// returning null on failureItem::findByHashid($hashid); // Finding a model based on the provided hashid or// throwing a ModelNotFoundException on failureItem::findByHashidOrFail($hashid); // Decoding a hashid to the integer id$item->hashidToId($hashid); // Getting the name of the hashid connection$item->getHashidsConnection();
You can learn more about this package, get full installation instructions, and view the source code on GitHub at mtvs/eloquent-hashids.