PHPackages                             veelasky/laravel-hashid - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. veelasky/laravel-hashid

ActiveLibrary[Database &amp; ORM](/categories/database)

veelasky/laravel-hashid
=======================

HashId Implementation on Laravel Eloquent ORM

v3.2.3(5mo ago)46168.5k↑10.7%17[3 PRs](https://github.com/veelasky/laravel-hashid/pulls)3MITPHPPHP ^8.1CI passing

Since Jan 22Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/veelasky/laravel-hashid)[ Packagist](https://packagist.org/packages/veelasky/laravel-hashid)[ RSS](/packages/veelasky-laravel-hashid/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (9)Versions (26)Used By (3)

Laravel HashId
==============

[](#laravel-hashid)

[![CI/CD Pipeline](https://github.com/veelasky/laravel-hashid/workflows/CI%2FCD%20Pipeline/badge.svg)](https://github.com/veelasky/laravel-hashid/workflows/CI%2FCD%20Pipeline/badge.svg)[![🔒 Security Scanning](https://github.com/veelasky/laravel-hashid/workflows/%F0%9F%94%92%20Security%20Scanning/badge.svg)](https://github.com/veelasky/laravel-hashid/workflows/%F0%9F%94%92%20Security%20Scanning/badge.svg)[![Codacy Badge](https://camo.githubusercontent.com/07ac49a029919cb41db9bbc01b1416c39e2ea4b2bfc0a770145a75ab5fd6a619/68747470733a2f2f6170692e636f646163792e636f6d2f70726f6a6563742f62616467652f47726164652f3365393239623533323761393435336262306461356362663265636238373934)](https://app.codacy.com/gh/veelasky/laravel-hashid?utm_source=github.com&utm_medium=referral&utm_content=veelasky/laravel-hashid&utm_campaign=Badge_Grade)[![codecov](https://camo.githubusercontent.com/79417fbc33dfb2d781536c894a1f109947abae8feae4e4f5e043b7a579ae0c1e/68747470733a2f2f636f6465636f762e696f2f67682f7665656c61736b792f6c61726176656c2d6861736869642f6272616e63682f6d61737465722f67726170682f62616467652e7376673f746f6b656e3d743935796d734d794458)](https://codecov.io/gh/veelasky/laravel-hashid)[![Latest Stable Version](https://camo.githubusercontent.com/096f2617478fc860725660f351f25f924dbc49467f4daefd3cb8192e2c866926/68747470733a2f2f706f7365722e707567782e6f72672f7665656c61736b792f6c61726176656c2d6861736869642f76)](//packagist.org/packages/veelasky/laravel-hashid)[![StyleCI](https://camo.githubusercontent.com/3982ed2d9870fff48d035dc77f64ce91e6a4533910b3bd5d536c8affafa8beb3/68747470733a2f2f6769746875622e7374796c6563692e696f2f7265706f732f3131383432343634332f736869656c643f6272616e63683d6d6173746572)](https://github.styleci.io/repos/118424643?branch=master)[![Total Downloads](https://camo.githubusercontent.com/e9f2689f83ab7277f9a474fcff526fb875fb337e97b043ddfd236ebbc82cf651/68747470733a2f2f706f7365722e707567782e6f72672f7665656c61736b792f6c61726176656c2d6861736869642f646f776e6c6f616473)](//packagist.org/packages/veelasky/laravel-hashid)[![Dependents](https://camo.githubusercontent.com/d3f51e23bf67404bdbbf04e4be4b4b0b140940d91ac73194adfe52e1ccfcbb14/68747470733a2f2f706f7365722e707567782e6f72672f7665656c61736b792f6c61726176656c2d6861736869642f646570656e64656e7473)](//packagist.org/packages/veelasky/laravel-hashid)[![License](https://camo.githubusercontent.com/6299c0507a10be00420e2fb2b7bc98e932c013b811dd8a21719f34578324914f/68747470733a2f2f706f7365722e707567782e6f72672f7665656c61736b792f6c61726176656c2d6861736869642f6c6963656e7365)](//packagist.org/packages/veelasky/laravel-hashid)

> Automatic HashId generator for your Laravel Eloquent models.

About
-----

[](#about)

Laravel HashId provides an elegant way to add hashed IDs to your Eloquent models. It generates unique, non-sequential hashes for your model IDs and provides convenient methods to work with them.

✨ Latest Features
-----------------

[](#-latest-features)

**Version 3.2.3** introduces automatic route key generation, eliminating boilerplate code, along with enhanced secure route model binding and powerful column selection capabilities for full Laravel 11/12 and PHP 8.4 compatibility.

### 🚀 Automatic Route Key Generation (New in v3.2.3)

[](#-automatic-route-key-generation-new-in-v323)

**Zero boilerplate:** The `HashableId` trait now automatically provides `getRouteKey()` method:

```
class User extends Model
{
    use HashableId;
    // getRouteKey() automatically returns hash - no implementation needed!
}

route('users.show', $user); // Automatically generates: /users/k1jTdv6l
```

### 🔒 Secure Route Model Binding (New in v3.2.2)

[](#-secure-route-model-binding-new-in-v322)

**Security improvement:** Route model binding now only accepts valid hash values by default, preventing predictable ID enumeration attacks:

```
class User extends Model
{
    use HashableId;
    // Default: only hash resolution, numeric IDs return 404
}

// ✅ Secure: /users/k1jTdv6l works
// ❌ Blocked: /users/1 returns 404 (prevents ID enumeration)
```

### 🔥 Column Selection API (New in v3.2.0)

[](#-column-selection-api-new-in-v320)

```
// Get user by hash with specific columns (better performance!)
$user = User::byHash($hash, ['name', 'email']);

// Get user by hash with single column
$user = User::byHash($hash, ['name']);

// Column selection with exception handling
$user = User::byHashOrFail($hash, ['name', 'email']);
```

**Benefits:**

- 🚀 **Better Performance** - Load only the columns you need
- 🔒 **Type Safety** - Automatic primary key inclusion when required
- 🔄 **Backward Compatible** - All existing code works unchanged
- 🎯 **Smart Defaults** - `['*']` loads all columns, just like before
- 🛡️ **Enhanced Security** - Prevents ID enumeration attacks by default
- ✅ **Zero Boilerplate** - No manual `getRouteKey()` implementation needed

Compatibility
-------------

[](#compatibility)

### Modern Laravel Support (Recommended)

[](#modern-laravel-support-recommended)

Laravel HashIdPHP VersionLaravel 10Laravel 11Laravel 12**3.2** 🌟**≥ 8.1**✅✅✅**4.x** 🚀**≥ 8.1**✅✅✅- 🌟 **Stable Release (3.2)** - Recommended for production
- 🚀 **Development Branch (4.x)** - Latest improvements

### Full Version Matrix

[](#full-version-matrix)

Laravel HashIdPHP VersionLaravel 6Laravel 7Laravel 8Laravel 9Laravel 10Laravel 11Laravel 12**1.x**`≥ 7.0`✅❌❌❌❌❌❌**2.x**`≥ 7.2`❌✅✅✅❌❌❌**3.0**`≥ 7.4`❌✅✅✅❌❌❌**3.1**`≥ 8.0`❌✅✅✅✅❌❌**3.2** 🌟`≥ 8.1`❌❌❌❌✅✅✅**4.x** 🚀`≥ 8.1`❌❌❌❌✅✅✅**📊 Version Recommendations:**

- **Laravel 6-9** → Use `3.0` or `3.1`
- **Laravel 10+** → Use `3.2` (stable) or `4.x` (development)
- **Latest features** → Use `3.2+` with column selection support

Installation
------------

[](#installation)

```
composer require veelasky/laravel-hashid
```

With Laravel's package auto-discovery, the package will be automatically registered.

Quick Start
-----------

[](#quick-start)

Simply add the `HashableId` trait to any Eloquent model you want to use with HashId:

```
use Illuminate\Database\Eloquent\Model;
use Veelasky\LaravelHashId\Eloquent\HashableId;

class User extends Model
{
    use HashableId;
}
```

Usage Examples
--------------

[](#usage-examples)

### Basic Usage

[](#basic-usage)

```
$user = User::find(1);           // Find user by ID
$user->hash;                     // Get HashId automatically

// Find by HashId
$user = User::byHash($hash);
$user = User::byHashOrFail($hash); // Throws exception if not found

// Convert between ID and HashId
$hashedId = User::idToHash($id);
$originalId = User::hashToId($hash);

// Query scope
User::query()->byHash($hash)->get();
```

### Column Selection (New in v3.2)

[](#column-selection-new-in-v32)

```
// Load only specific columns for better performance
$user = User::byHash($hash, ['name', 'email']);

// Single column selection
$user = User::byHash($hash, ['name']);

// Column selection with exception handling
$user = User::byHashOrFail($hash, ['name', 'email']);
```

### Persisting HashId to Database

[](#persisting-hashid-to-database)

```
class User extends Model
{
    use HashableId;

    protected $shouldHashPersist = true;  // Persist hash to database
    protected $hashColumnName = 'hashid';  // Custom column name (optional)
}
```

### Route Model Binding

[](#route-model-binding)

The trait automatically overwrites route methods to use HashId:

```
Route::get('/users/{user}', [UserController::class, 'show']);

class UserController
{
    public function show(User $user)
    {
        // $user resolves automatically by HashId
        // Example URL: /users/k1jTdv6l
        // Numeric IDs like /users/1 will return 404 by default (secure!)
    }
}
```

#### 🔒 Secure Route Model Binding (Default)

[](#-secure-route-model-binding-default)

By default, route model binding only accepts valid hash values and returns 404 for plain numeric IDs, preventing predictable ID enumeration attacks:

```
class User extends Model
{
    use HashableId;
    // $bindingFallback = false; // Default behavior - only hash resolution
}

// ✅ This works: /users/k1jTdv6l
// ❌ This returns 404: /users/1 (prevents ID enumeration)
```

#### Optional Fallback to Numeric ID

[](#optional-fallback-to-numeric-id)

If you need to support both hash and numeric ID resolution (not recommended for production), you can enable the fallback:

```
class User extends Model
{
    use HashableId;

    protected $bindingFallback = true; // Allow both hash and numeric ID resolution
}

// ✅ Both work: /users/k1jTdv6l AND /users/1
```

#### Custom Field Binding

[](#custom-field-binding)

Custom field binding always uses Laravel's default behavior:

```
Route::get('/users/{user:slug}', [UserController::class, 'show']);

// This will resolve by 'slug' field, not by hash
```

#### 🚀 Automatic Route Key Generation (New in v3.2.3)

[](#-automatic-route-key-generation-new-in-v323-1)

The `HashableId` trait now automatically provides `getRouteKey()` method, so you don't need to implement it manually:

```
class User extends Model
{
    use HashableId;
    // No manual getRouteKey() implementation needed!
}

// Route generation now automatically uses hash
route('users.show', $user); // Generates: /users/k1jTdv6l
```

**Before this version:**

```
class User extends Model
{
    use HashableId;

    // Manual implementation was required
    public function getRouteKey() {
        return $this->hash;
    }
}
```

**Benefits:**

- ✅ **Zero Boilerplate** - No manual `getRouteKey()` implementation needed
- 🔄 **Automatic** - Works out of the box with the trait
- 🛡️ **Consistent** - Uses the same hash values as route resolution
- 🔧 **Configurable** - Respects custom hash column names
- ⬅️ **Backward Compatible** - Existing custom implementations still work

### Validation Rules

[](#validation-rules)

```
use App\Models\User;
use Veelasky\LaravelHashId\Rules\ExistsByHash;

$request->validate([
    'user_id' => ['required', new ExistsByHash(User::class)],
]);
```

### Advanced Usage

[](#advanced-usage)

#### Repository Pattern Access

[](#repository-pattern-access)

```
// Using the HashId facade
$hashedId = HashId::idToHash($id, User::class);
$originalId = HashId::hashToId($hash, User::class);

// Manual hash ID creation
$hashId = HashId::make('custom-key', 'custom-salt');
```

#### Shared Hash Across Models

[](#shared-hash-across-models)

```
class User extends Model
{
    protected $hashKey = 'shared-hash-key';
}

class Customer extends User { }

$customer = Customer::find(1);
$user = User::find(1);

// Both will have the same hash
echo $customer->hash === $user->hash; // true
```

Configuration
-------------

[](#configuration)

You can configure HashId behavior using environment variables:

```
HASHID_SALT=your-custom-salt
HASHID_LENGTH=10
HASHID_ALPHABET=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890
```

Or publish the configuration file:

```
php artisan vendor:publish --tag=laravel-hashid-config
```

License
-------

[](#license)

MIT License. Feel free to use this package in your projects!

###  Health Score

61

—

FairBetter than 99% of packages

Maintenance74

Regular maintenance activity

Popularity47

Moderate usage in the ecosystem

Community26

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~124 days

Recently: every ~163 days

Total

24

Last Release

174d ago

Major Versions

v1.0.5 → v2.0.02021-01-03

v2.2.0 → v3.0.02022-02-09

PHP version history (5 changes)v1.0.0PHP &gt;=7.0.0

v2.0.0PHP ^7.2 || ^8.0

v3.0.0PHP ^7.4 || ^8.0

v3.1.0PHP ^8.0

v3.2.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/4bca066a038d018921641b2d7134764d18f23b761b08bdbe1c9819f4d92dceed?d=identicon)[veelasky](/maintainers/veelasky)

---

Top Contributors

[![veelasky](https://avatars.githubusercontent.com/u/1797358?v=4)](https://github.com/veelasky "veelasky (54 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (41 commits)")[![muhajirinlpu](https://avatars.githubusercontent.com/u/13056772?v=4)](https://github.com/muhajirinlpu "muhajirinlpu (5 commits)")[![vctrtvfrrr](https://avatars.githubusercontent.com/u/1169416?v=4)](https://github.com/vctrtvfrrr "vctrtvfrrr (4 commits)")[![kohlerdominik](https://avatars.githubusercontent.com/u/18621527?v=4)](https://github.com/kohlerdominik "kohlerdominik (3 commits)")[![IndyIndyIndy](https://avatars.githubusercontent.com/u/2108907?v=4)](https://github.com/IndyIndyIndy "IndyIndyIndy (2 commits)")[![codacy-badger](https://avatars.githubusercontent.com/u/23704769?v=4)](https://github.com/codacy-badger "codacy-badger (1 commits)")[![Mondotosz](https://avatars.githubusercontent.com/u/55015209?v=4)](https://github.com/Mondotosz "Mondotosz (1 commits)")[![PyaeSoneAungRgn](https://avatars.githubusercontent.com/u/44226349?v=4)](https://github.com/PyaeSoneAungRgn "PyaeSoneAungRgn (1 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (1 commits)")[![gojirian](https://avatars.githubusercontent.com/u/4308070?v=4)](https://github.com/gojirian "gojirian (1 commits)")[![jonhassall](https://avatars.githubusercontent.com/u/9570507?v=4)](https://github.com/jonhassall "jonhassall (1 commits)")[![EriBloo](https://avatars.githubusercontent.com/u/19932449?v=4)](https://github.com/EriBloo "EriBloo (1 commits)")

---

Tags

eloquenthacktoberfesthashhashidhashidshashinglaravellaravel-hashidlaravellumeneloquenthashidshashid

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/veelasky-laravel-hashid/health.svg)

```
[![Health](https://phpackages.com/badges/veelasky-laravel-hashid/health.svg)](https://phpackages.com/packages/veelasky-laravel-hashid)
```

###  Alternatives

[cviebrock/eloquent-sluggable

Easy creation of slugs for your Eloquent models in Laravel

4.0k13.6M253](/packages/cviebrock-eloquent-sluggable)[watson/validating

Eloquent model validating trait.

9723.3M47](/packages/watson-validating)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[cviebrock/eloquent-taggable

Easy ability to tag your Eloquent models in Laravel.

567694.8k3](/packages/cviebrock-eloquent-taggable)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
