PHPackages                             adamhopkinson/laravel-model-hash - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. adamhopkinson/laravel-model-hash

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

adamhopkinson/laravel-model-hash
================================

A trait which automatically generates a unique hash per model instance

1.2.0(5y ago)2318.7k↑51%2MITPHPCI failing

Since Jul 23Pushed 4y ago1 watchersCompare

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

READMEChangelog (4)Dependencies (3)Versions (7)Used By (0)

laravel-model-hash
==================

[](#laravel-model-hash)

**Automatically create short hashes for your Laravel models, automatically use them in urls and back-fill existing models.**

[![Build & Test Status](https://github.com/adamhopkinson/laravel-model-hash/workflows/Build%20&%20Test%20Status/badge.svg)](https://github.com/adamhopkinson/laravel-model-hash/workflows/Build%20&%20Test%20Status/badge.svg)

Why?
----

[](#why)

Database IDs in URLs such as [stackoverflow.com/users/12280](https://stackoverflow.com/users/12280) never quite feel ok to me

- having the index of an entity allows website size and growth to be estimated
- accessing something that shouldn't be accessible is just a careless developer and a curious visitor away

But at the same time, I didn't want to completely replace the database ID with a UUID, as some packages do - as I was nervous about how this might affect performance.

laravel-model-hash allows you to generate a short, random hash when an item is created while still using auto-incrementing IDs for database relationships.

### How it works

[](#how-it-works)

This package provides a trait which - when attached to a model - creates a random string hash when new instances of the model are created.

The hash is created by shuffling an *alphabet*, taking the first *length* characters, and checking for uniqueness in the database (up to a maximum number of times). If a unique hash wasn't found within the *maximum attempts*, an exception of type `UniqueHashNotFoundException` will be thrown and the model instance will not be saved.

The package is configured either globally using a config file, or by defining model-specific properties.

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

[](#installation)

You can install the package via Composer:

```
composer require adamhopkinson/laravel-model-hash

```

If you would like to tweak any of the package configuration, you must first publish the config file:

```
php artisan vendor:publish --provider="AdamHopkinson\LaravelModelHash\LaravelModelHashServiceProvider"

```

Usage
-----

[](#usage)

To add a hash to model, add the `LaravelModelHash` trait:

```
use AdamHopkinson\LaravelModelHash\Traits\ModelHash;

class MyModel extends Model
{
    use ModelHash;
    //...
}

```

And create a migration to add a field to store the hash - by default, the field is called `hash` and has a length of 5:

```
$table->string('hash', 5)->unique()->index();

```

You may add a unique and index flag for database performance improvements. If you're adding this trait to an existing model, you will need to use `nullable()` until all records have a hash.

Now, when new instances of the model are created, they will be assigned a random string.

### Adding hashes to existing models

[](#adding-hashes-to-existing-models)

If you are adding this package to an existing installation, there is an artisan command to 'backfill' existing models. The syntax is:

```
php artisan laravelmodelhash:populate

```

This uses reflection to find all models (in `app_path()`) which extend the `ModelHash` trait, and adds hash values to any records where the hash is currently `null`.

If you would like to only run this for a specific model, use the `--model` (or `-M`) option - but *remember to double-slash the namespace*:

```
php artisan laravelmodelhash:populate --model \\App\\MyModel

```

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

[](#configuration)

There are three configurable parts to the hash:

- the alphabet used (ie the set of allowed characters)
- the name of the hash field
- the length of the hash

And two other configuration properties

- the maximum number of attempts to find a hash which isn't already present in the database before an exception is thrown
- whether to automatically use the hash in route model binding

Each of these is set in the default configuration, which can be overridden in `/config/laravelmodelhash.php` (this must first be published - see the Installation section for details).

If you want to change these settings per model, they can be changed by adding the following model properties:

```
protected $hashName; // string
protected $hashLength; // int
protected $hashAlphabet; // string
protected $hashMaximumAttempts; // int
protected $useHashInRoutes; // boolean

```

Thanks
------

[](#thanks)

I've gotten this far thanks to the following:

- [John Braun](https://github.com/Jhnbrn90) and his excellent guide to [Laravel Package Development](https://laravelpackage.com/)
- [Jeff Way](https://github.com/JeffreyWay) of [Laracasts](https://laracasts.com/) fame
- the amazing Laravel community

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity37

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 96.8% of commits — single point of failure

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 ~5 days

Total

4

Last Release

2109d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1493635?v=4)[Adam Hopkinson](/maintainers/adamhopkinson)[@adamhopkinson](https://github.com/adamhopkinson)

---

Top Contributors

[![adamhopkinson](https://avatars.githubusercontent.com/u/1493635?v=4)](https://github.com/adamhopkinson "adamhopkinson (60 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")

---

Tags

laravelmodeltraitkeyid

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/adamhopkinson-laravel-model-hash/health.svg)

```
[![Health](https://phpackages.com/badges/adamhopkinson-laravel-model-hash/health.svg)](https://phpackages.com/packages/adamhopkinson-laravel-model-hash)
```

###  Alternatives

[cybercog/laravel-optimus

An Optimus bridge for Laravel. Id obfuscation based on Knuth's multiplicative hashing method.

192564.1k](/packages/cybercog-laravel-optimus)[fanmade/laravel-bitwise-trait

Simple trait to use bitwise operators on any class

1570.7k](/packages/fanmade-laravel-bitwise-trait)[iteks/laravel-enum

A comprehensive Laravel package providing enhanced enum functionalities, including attribute handling, select array conversions, and fluent facade interactions for robust enum management in Laravel applications.

2516.7k](/packages/iteks-laravel-enum)[mlezcano1985/laravel-pivot-soft-deletes

Soft delete Eloquent pivot models using Laravel SoftDeletes trait.

186.8k](/packages/mlezcano1985-laravel-pivot-soft-deletes)[infocyph/uid

UUID (RFC 4122 + Unofficial/Draft), ULID, Snowflake ID, Sonyflake ID, TBSL (library exclusive) generator!

105.1k](/packages/infocyph-uid)

PHPackages © 2026

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