PHPackages                             jacknoordhuis/laravel-database-hashing - 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. jacknoordhuis/laravel-database-hashing

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

jacknoordhuis/laravel-database-hashing
======================================

A package for automatically hashing Eloquent attributes in Laravel 5.5+.

2.0.0(7y ago)1162.4k2[1 issues](https://github.com/JackNoordhuis/laravel-database-hashing/issues)LGPL-3.0-or-laterPHPPHP &gt;=7.2.0

Since Nov 6Pushed 7y ago3 watchersCompare

[ Source](https://github.com/JackNoordhuis/laravel-database-hashing)[ Packagist](https://packagist.org/packages/jacknoordhuis/laravel-database-hashing)[ Docs](https://github.com/JackNoordhuis/laravel-database-hashing)[ RSS](/packages/jacknoordhuis-laravel-database-hashing/feed)WikiDiscussions master Synced yesterday

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

Laravel 5.5+ Database Hashing package
=====================================

[](#laravel-55-database-hashing-package)

*A package for automatically hashing Eloquent attributes!*

[![Build Status](https://camo.githubusercontent.com/e66d3e435e144696338fb6faf7e2747408307e5c5fc93c8ba6da2587d3ba432a/68747470733a2f2f7472617669732d63692e6f72672f4a61636b4e6f6f7264687569732f6c61726176656c2d64617461626173652d68617368696e672e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/JackNoordhuis/laravel-database-hashing)

The purpose of this library is to create a set-it-and-forget-it package that can be installed without much effort to hash eloquent model attributes stored in your database tables.

When enabled, this package will automatically hash the data assigned to attributes that you've specified as they are updated. This allows you to hide the plain text value of attributes and maintain the ability search the database for the value (the same input data will always provide the same hash).

All data hashed by this package will have an application specific salt which is specified in the configuration or environment files, so hashing the same data with a different salt in another application will result in a different output. This adds layer of complexity/protection against attackers who try to reconstruct your data by attempting to brute force a hash. If this is not enough, this package also supports providing a secondary salt on top of the application salt, but this cannot be configured to automatically apply to attributes out of the box.

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

[](#installation)

### Step 1: Composer

[](#step-1-composer)

Via command line:

```
$ composer require jacknoordhuis/laravel-database-hashing ^2.0
```

Or add the package to your `composer.json`:

```
{
    "require": {
        "jacknoordhuis/laravel-database-hashing": "^2.0"
    }
}
```

### Step 2: Enable the package

[](#step-2-enable-the-package)

This package implements Laravel 5.5's package auto-discovery feature. After you install it the package provider and facade are registered automatically.

If you would like to explicitly declare the provider and/or alias, you can do so by first adding the service provider to your `config/app.php` file:

```
'providers' => [
    //
    \jacknoordhuis\database\hashing\HashingServiceProvider::class,
];
```

And then add the alias to your `config/app.php` file:

```
'aliases' => [
    //
    'DatabaseHashing' => \jacknoordhuis\database\hashing\HashingFacade::class,
];
```

### Step 3: Configure the package

[](#step-3-configure-the-package)

Publish the package config file:

```
$ php artisan vendor:publish --provider="jacknoordhuis\database\hashing\HashingServiceProvider"
```

You may now enable automatic hashing of eloquent models by editing the `config/database-hashing.php` file:

```
return [
    "enabled" => env("DB_HASHING_ENABLED", true),
];
```

Or simply setting the the `DB_HASHING_ENABLED` environment variable to true, via the Laravel `.env` file or hosting environment.

```
DB_HASHING_ENABLED=true
```

Usage
-----

[](#usage)

Use the `HasHashedAttributes` trait in any eloquent model that you wish to apply automatic attribute hashing to and define a `protected $hashing` array containing an array of the attributes to automatically hash.

For example:

```
use jacknoordhuis\database\hashing\traits\HasHashedAttributes;

class User extends Model
{
    use HasHashedAttributes;

    /**
     * The attributes that should be hashed when set.
     *
     * @var array
     */
    protected $hashing = [
        'username_lookup',
    ];
}
```

### Looking up hashed values

[](#looking-up-hashed-values)

You can lookup hashed values in your database tables by simply hashing the value you're searching for, as the resulting hash will always be the same.

```
$user->username_lookup = $request->get('username'); //the username_lookup attribute will be automatically hashed

//when our user tries to login we just search the database for the hashed value of their username
$user = User::where('username_lookup', DatabaseHashing::create($request->get("username"))->first();
```

You can also optionally provide a salt modifier when hashing data directly, which adds another level of complexity/security on top of the application-level salt.

```
//with a salt modifier so we can only ever re-create the hash when the user provides their email or we could store an
//encrypted copy ourselves with another package
$user->username_lookup = $request->get('username'); //set the attribute, then hash manually because we use a modifier
$user->hashAttribute('username_lookup', $request->get('username')); //this time add the plain text email as a salt modifier

//when a user provides their email when logging in, we can replicate the hash and search for the user in the database.
$user = User::where('username_lookup', DatabaseHashing::create($request->get("username"), $request->get("email")))->first();
```

FAQ's
-----

[](#faqs)

### Can I manually hash arbitrary data?

[](#can-i-manually-hash-arbitrary-data)

Yes! You can manually hash any string using the `DatabaseHashing::create()` global facade.

For example:

```
    //hash with only application salt
    $hashedEmail = DatabaseHashing::create(Input::get('email'));

    //hash with application salt AND salt modifier
    $hashedEmail = DatabaseHashing::create(Input::get("email"), Input::get('password'));
```

### Can I hash all my model data?

[](#can-i-hash-all-my-model-data)

No! The hashing process is irreversible, meaning it should only be used for creating (pseudonymous) identifiers so that it is still possible to look up data in your database. If you want to *encrypt* your data use a package like [laravel-database-encryption](https://github.com/austinheap/laravel-database-encryption).

### Should I hash numeric auto-incrementing identifiers?

[](#should-i-hash-numeric-auto-incrementing-identifiers)

Probably not. If all data stored in your database is encrypted or hashed then the numeric identifier is effectively anonymous (it's really pseudonymous) so there is no way to associate any human readable data with the identifier. There are other reasons for not hashing or encrypting the primary key in your database, and you can read about those [here](https://stackoverflow.com/a/34423898).

### Compatibility with the laravel-database-encryption package

[](#compatibility-with-the-laravel-database-encryption-package)

By default these two packages will conflict but we can get around this by implementing our own `setAttribute()` method that calls both the packages implementations as well:

```
class User extends Authenticatable
{
    use Notifiable, HasEncryptedAttributes, HasHashedAttributes {
        HasEncryptedAttributes::setAttribute as setEncryptedAttribute;
        HasHashedAttributes::setAttribute as setHashedAttribute;
    }

    protected $fillable = [
        'name', 'email', 'email_lookup', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $encrypted = [
        'name', 'email',
    ];

    protected $hashing = [
        'email_lookup',
    ];

    /**
     * Overwrite the method so we can attempt to encrypt OR hash an
     * attribute without the traits colliding.
     *
     * @param string $key
     * @param mixed $value
     */
    public function setAttribute($key, $value)
    {
        $this->setEncryptedAttribute($key, $value); //attempt to encrypt the attribute

        $current = $this->attributes[$key] ?? null; //fetch the current value of the attribute
        if($current === $value) { //check to make sure the attribute wasn't modified (we will never hash an encrypted attribute)
            $this->setHashedAttribute($key, $value); //attempt to hash the attribute
        }
    }
}
```

This can be extracted into it's own trait if it is needed across multiple models in your project. This same approach can also be used to make any package that implements the `setAttribute()` method on models compatible.

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity30

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~58 days

Total

3

Last Release

2628d ago

Major Versions

1.0.1 → 2.0.02019-03-03

PHP version history (2 changes)1.0.0PHP &gt;=7.1.0

2.0.0PHP &gt;=7.2.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/10399774?v=4)[Jack Noordhuis](/maintainers/JackNoordhuis)[@JackNoordhuis](https://github.com/JackNoordhuis)

---

Top Contributors

[![JackNoordhuis](https://avatars.githubusercontent.com/u/10399774?v=4)](https://github.com/JackNoordhuis "JackNoordhuis (35 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jacknoordhuis-laravel-database-hashing/health.svg)

```
[![Health](https://phpackages.com/badges/jacknoordhuis-laravel-database-hashing/health.svg)](https://phpackages.com/packages/jacknoordhuis-laravel-database-hashing)
```

###  Alternatives

[anourvalar/eloquent-serialize

Laravel Query Builder (Eloquent) serialization

11320.2M21](/packages/anourvalar-eloquent-serialize)[overtrue/laravel-versionable

Make Laravel model versionable.

585308.0k5](/packages/overtrue-laravel-versionable)[abbasudo/laravel-purity

elegant way to add filter and sort in laravel

514330.5k1](/packages/abbasudo-laravel-purity)[statamic-rad-pack/runway

Eloquently manage your database models in Statamic.

135192.6k5](/packages/statamic-rad-pack-runway)[dragon-code/laravel-deploy-operations

Performing any actions during the deployment process

240173.5k2](/packages/dragon-code-laravel-deploy-operations)[stayallive/laravel-eloquent-observable

Register Eloquent model event listeners just-in-time directly from the model.

2928.9k7](/packages/stayallive-laravel-eloquent-observable)

PHPackages © 2026

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