erashdan / hashid
Simple package to hash eloquent primary key
Installs: 7 506
Dependents: 0
Suggesters: 0
Security: 0
Stars: 9
Watchers: 2
Forks: 2
Open Issues: 4
Requires
- php: >=7.1.3
- hashids/hashids: ^3.0
- illuminate/container: ~5.3.0|~5.4.0|~5.5.0|~5.6.0|~5.7.0|~5.8.0|^6.0|^7.0
- illuminate/contracts: ~5.3.0|~5.4.0|~5.5.0|~5.6.0|~5.7.0|~5.8.0|^6.0|^7.0
- illuminate/database: ~5.4.0|~5.5.0|~5.6.0|~5.7.0|~5.8.0|^6.0|^7.0
Requires (Dev)
- orchestra/testbench: ~3.4.2|~3.5.0|~3.6.0|~3.7.0|~3.8.0|^4.0|^7.0
- phpunit/phpunit: ^5.7|6.2|^7.0
This package is auto-updated.
Last update: 2025-01-26 01:18:52 UTC
README
This package hashes the primary key of an eloquent record.
// Get Hash ID $user = \App\User::first(); $user->hashed_id; //x7LR5oQJleJX60yPpNWV
Installation
This package can be used in Laravel 5.5 or higher.
You can install the package via composer:
composer require erashdan/hashid
Laravel's package auto discovery will automatically register the service provider for you.
Then you need to publish the configuration to your project:
php artisan vendor:publish --provider="Erashdan\Hashid\HashidServiceProvider" --tag="config"
And add the key used for the hashing in .env file
HASHID_KEY=SET_YOUR_KEY
OR
Use Laravel's own app key, change the key parameter in config/hashid.php
to Laravel's application key
'key' => env('APP_KEY'),
You can also change the length of the resulted hash from .env
file.
HASHID_LENGTH=6
Usage
Eloquent by default doesn't implement hashid, so you should use the trait provided from the package.
use Illuminate\Database\Eloquent\Model; use Erashdan\Hashid\Traits\Hashid; class Post extends Model { use Hashid;
You can then use the hashed_id attribute on the eloquent object itself.
$post = \App\Post::first(); $post->hashed_id; //x7LR5oQJleJX60yPpNWV
Or find a resource by hash
$post = \App\Post::FindOrFailHashed('x7LR5oQJleJX60yPpNWV'); $post->id; //1
Validation
You can validate if hashed id is existed in model or not
request()->validate([ 'post_id' => 'hashed_exists:' . \App\Post::class ]);
Testing
composer test
Credits
TODO
- [x] Build dev version.
- [] Create command for key generater.
- [] Can store hash id on database.
- [] Can be cached.