Installation:
composer require veelasky/laravel-hashid
Publish the config (optional):
php artisan vendor:publish --provider="Veelasky\HashId\HashIdServiceProvider" --tag="hashid-config"
Enable for a Model:
Add the HasHashId trait to your Eloquent model:
use Veelasky\HashId\HasHashId;
class User extends Model
{
use HasHashId;
}
First Use Case:
Access the hashed ID via $model->hashId or $model->getHashId().
Retrieve the original ID from a hash:
$user = User::where('hash_id', 'abc123')->first();
$originalId = $user->id; // Original ID
config/hashid.php for default settings (e.g., alphabet, min_length, salt).$hashIdConfig in the model:
protected $hashIdConfig = [
'alphabet' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
'min_length' => 10,
];
Generating Hashes:
save()/create() if $hashId is empty.$model->generateHashId();
Querying by Hash:
hash_id in queries:
User::where('hash_id', 'abc123')->get();
User::byHashId('abc123')->first();
URL-Friendly IDs:
route('users.show', ['user' => $user->hashId]); // /users/abc123
Migrations:
hash_id column to your table:
Schema::table('users', function (Blueprint $table) {
$table->string('hash_id')->unique()->nullable();
});
API Responses:
return User::find($id)->append('hash_id');
hash_id in API responses to hide internal IDs.hash_id in URLs or forms for user-friendly interactions.hash_id for faster lookups:
Cache::remember("user:{$hashId}", now()->addHours(1), fn() => User::byHashId($hashId)->first());
hash_id format in forms:
$request->validate(['hash_id' => 'required|string|hashid']);
Collision Risk:
Performance:
Model::all()). Use ->pluck('hash_id') instead.Database Indexing:
hash_id is indexed for query performance:
Schema::table('users', function (Blueprint $table) {
$table->string('hash_id')->unique()->index();
});
Salt Management:
salt, ensure it’s consistent across environments (configured in .env or config/hashid.php).Model Events:
creating and updating events. Override these if custom logic is needed:
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if (!$model->hash_id) {
$model->generateHashId();
}
});
}
HashId::decode($hash) to check if a hash is valid:
if (!HashId::decode($hash)) {
abort(404, 'Invalid hash ID');
}
config/hashid.php to log hash generation:
'debug' => env('HASHID_DEBUG', false),
Custom Alphabets:
protected $hashIdConfig = [
'alphabet' => 'custom-alphabet-here',
];
Hash Length:
min_length to balance readability and collision risk (default: 8).Custom Storage:
Testing:
HashId in tests to avoid flakiness:
HashId::shouldReceive('encode')->andReturn('test123');
Fallbacks:
hash_id might be missing (e.g., legacy data):
$id = $model->hash_id ?? $model->id;
How can I help you explore Laravel packages today?