erashdan/hashid

This package is abandoned and no longer maintained. No replacement package was suggested.
There is no license information available for the latest version (1.1.0) of this package.

Simple package to hash eloquent primary key

1.1.0 2021-01-05 13:37 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.