vinkla/hashids
Laravel bridge for Hashids: encode integers into short, non-sequential strings and decode them back. Supports multiple connections via config, includes a facade and manager for dependency injection, and integrates cleanly with typical Laravel workflows.
composer require vinkla/hashids.php artisan vendor:publish to generate config/hashids.php.config/hashids.php—set a unique salt (critical for security), desired length, and optional alphabet (e.g., remove 0O1l to avoid user confusion).use Vinkla\Hashids\Facades\Hashids;
$hash = Hashids::encode(42); // e.g., 'xW'
$ids = Hashids::decode('xW'); // [42]
First use case: obfuscating Eloquent IDs in public URLs (e.g., /posts/42 → /posts/xW).decode() in custom route binding to resolve models from hashed IDs:
Route::bind('post', function ($hash) {
[$id] = Hashids::decode($hash) ?: [];
return Post::findOrFail($id);
});
return response()->json(['id' => Hashids::encode($user->id)]);
admin for internal logs, user-facing for customer URLs) with unique salts and alphabets:
Hashids::connection('user-facing')->encode($productId); // Safe for public use
HashidsManager in constructors for testability and avoids global state:
public function __construct(HashidsManager $hashids) { $this->hashids = $hashids; }
salt, alphabet, or min_hash_length breaks all existing hashes—migrate cautiously (e.g., store original IDs if re-encoding is needed).decode() always returns an array—even for single IDs—so use safe destructuring:
[$id] = Hashids::decode($hash) ?: []; // Avoids "undefined offset" errors
encode() returns "0" for non-integers (e.g., strings, null) without throwing—validate inputs first.0/O, 1/l/I in alphabet config when hashes are displayed to users (e.g., URL paths) to reduce human error.config/hashids.php settings override defaults, but the hashids service is lazy-loaded—changes to config require no cache clear (unless using config caching: php artisan config:clear).sqids/sqids-php with manual DI) has near-identical API and better Unicode/ID requirements.How can I help you explore Laravel packages today?