A laravel package to generate model hashid based on model id column.

Overview

Laravel Model Hashid

A package to generate model hash id from the model auto increment id for laravel models

Installation

Require the package using composer:

composer require touhidurabir/laravel-model-hashid

To publish the config file:

php artisan vendor:publish --provider="Touhidurabir\ModelHashid\ModelHashidServiceProvider" --tag=config

How it can be helpful?

When developing public APIs, sometimes we need to provide data based on givem model id from the requester endpoint . For example

/some-end-point/some-model-resource/{id}

where the give {id} can be model table associated auto increament id . Using an uuid is one another and now a days a pretty popular appraoch to obsecure the model table id. such as

/some-end-point/some-model-resource/{uuid}

But even with uuid, we do need to make adjustment to query to find model resource based on uuid or make the uuid the Primary Key of the model.

However this packaga take a different approach where on model resource creation , it gegerate and store an unique hash id from the model id and then use that to pass as response to remote request . And the requester use that hashid to make request to APIs instead of id or uuid but applying the middlewares, those hashid in the route param or request param dehashed to original model id . So basically this happens,

$id = 1;
$hashid = 'jRlef2';

when making the api request, like this

/some-end-point/some-model-resource/{hashid}

Say that route url point to some controller method, then

class SomeController extends Controller {

    public function show(int $id) {

        // $id where will be 1, not jRlef2
    }
}

Config Options

The published config file contails few possible configuration options . See and read through the config/hasher.php to get to know all the possible options . But few important ones are

enable

'enable' => env('ID_HASHING', false),

Determine if Hashid should be enabled or not . By default it is set to true.

key

'key' => env('ID_HASHING_KEY', ''),

Use this unique key as the base or salt to generate the hash . It is not an required details but it is highly recommened to use one unique key through out the app to make the hashid stronger .

column

'column' => 'hash_id',

The define which column by default this package should look for hashid to retrive or store the gererated one. But still possible to have some column name here and then have something different in some models.

alphabets

'alphabets' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',

This defined the only characters that will be present in a hash string. Best To have along range of characters which by default is lower case a-z with upper case A-Z and 0-9.

NOTE : it must be at least 16 characters long and must only contains unique characters. no duplicate allowed like 'aaaabbbbbbcc' etc .

regeneration_job

'regeneration_job' => \Touhidurabir\ModelHashid\Jobs\ModelHashidRegeneratorJob::class,

This defined the job that will be used to run the update or fill up the missing hash id through the hashid:run command.

Command

This packaga includes a command that can use to set up the model hash id for the missing ones or update existing one . It will be helpful if this package included later in any laravel app that already have some data in it's tables and needed to set up hash id for those records. To utlize this command run

php artisan hashid:run User,Profile

The one argument it reuired is the name of the models command seperated(if there is multiple models to run for) . Behind the scene it calls a queue job to go through the model recored and work on those to update/fill hash id column value. Other options as follow

--path=

By default it assumes all the models are located in the App\Models\ namespace . But if it's located some where else , use the option to define the proper model space path with trailing slash .

--update-all

By default this command will only work with those model records that have the defined hash id column null . So basically it will fill up the missing ones , but if this false is provided with the command it will update all regardless of hashid associated with or not.

--on-job

This defined if this will update/fill missing one through a queue job . The command use a job where the main logic resides in . But by default it uses the framework provided dispatchNow method to run the jon in sync way . if the falg provided and queue configured properly, it will push the job in the queue .

--job=

If need to pass custom queue job implementation, it can be directly provided though this option . also one can update the queue class in the config file .

Usage

Use the trait IdHashable in model where uuid needed to attach

use Touhidurabir\ModelHashid\IdHashable;
use Illuminate\Database\Eloquent\Model;

class User extends Model {
    
    use IdHashable;
}

By default this package use the column name hash_id to store the hash value of the model auto increment id.but this can be changed

Also possible to override the uuid column and attaching event from each of the model . to do that need to place the following method in the model :

use Touhidurabir\ModelHashid\IdHashable;
use Illuminate\Database\Eloquent\Model;

class User extends Model {
    
    use IdHashable;

    /**
     * Get the name of hash column name
     *
     * @return string
     */
    public function getHashColumn() {

        return 'hash';
    }
}

Now to make hashed route or request params automatically, use this following 2 middlewares

Touhidurabir\ModelHashid\Http\Middleware\DehashRequestParams // this to dehash request post/get params
Touhidurabir\ModelHashid\Http\Middleware\DehashRouteParams // this to dehash route hash params such as /{id} as hash

Register these middlewares in Http\Kernel.php file or in controller/route file separately as require .

NOTE that the DehashRequestParams middleware can dehash request param that is String(simple hash string) or Array(array of hash string) only. So if require to handle complex param such as JSON string, need to handle that manually.

To handle such case where one need to decode some keys form a JSON response or for some other purpose need manual dehashing, this package provide 2 helper methods

  • decode_hashid
  • decode_hashids

As the name suggest, the decode_hashid can only work with a single hash where decode_hashids can work with single hash or array of hash.

Make sure to the put the hashid column name in migration file

$table->string('hash_id')->nullable()->unique()->index();

Or can be used with the combination of hasher config as such:

$table->string(config('hasher.column'))->nullable()->unique()->index();

This package also include some helper method that make it easy to find model records via UUID. for example

User::byHashId($hash)->where('active', true)->first(); // single hash id
User::byHashId([$hash1, $hash2])->where('active', true)->get(); // multiple hash id

Or simple and direct find

User::findByHashId($uhashuid); // single hash id
User::findByHashId([$hash1, $hash2]); // multiple hash id

The package also provide a bit of safe guard by checking if the model table has the given hash id column .

If the hash id column not found for model table schema, it will not create and attach an hash id.

Extras

For API resource

One big use case of this package for the development of API services where gthe developers do not want to include the model original auto incrementing id . For that case, one should use the hash_id as such

class User extends JsonResource {
    
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request) {

        return [
            'id'    => $this->hash_id,
            'email' => $this->email,
            ...
        ];
    }
}

The above approach is perfectly fine. Howeever as the hash id is not just used mostly for any other model related purpose , one may want to make it hidden like

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'hash_id',
];

For such case, this package includes a simple trait to use with the api resource classes,

use Touhidurabir\ModelHashid\IdHashing;

class User extends JsonResource {

    use IdHashing;
    
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request) {

        return [
            'id'    => $this->getId(),
            'email' => $this->email,
            ...
        ];
    }
}

Using the core Hasher class

The core of this package is the Hasher class that handle the whole hash decode/encode process. This is hightly dependent on the popular php Hashid Package with some bit of extra functionality . One can also use this hasher as for their need fits . To see the details of the hasher class and how it works, check the code itself at Touhidurabir\ModelHashid\Hasher\Hasher .

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

You might also like...
Laravel-model-mapper - Map your model attributes to class properties with ease.
Laravel-model-mapper - Map your model attributes to class properties with ease.

Laravel Model-Property Mapper This package provides functionality to map your model attributes to local class properties with the same names. The pack

This package helps you to add user based follow system to your model.

Laravel Follow User follow unfollow system for Laravel. Related projects: Like: overtrue/laravel-like Favorite: overtrue/laravel-favorite Subscribe: o

Laravel package to generate and to validate a UUID according to the RFC 4122 standard. Only support for version 1, 3, 4 and 5 UUID are built-in.

Laravel Uuid Laravel package to generate and to validate a universally unique identifier (UUID) according to the RFC 4122 standard. Support for versio

A package to generate modules for a Laravel project.

Laravel Modular A package to generate modules for a Laravel project. Requirements PHP 7.4 or greater Laravel version 8 Installation Install using comp

Laravel Package to generate CRUD Files using TALL Stack
Laravel Package to generate CRUD Files using TALL Stack

tall-crud-generator Laravel Package to generate CRUD Files using TALL Stack Requirements Make sure that Livewire is installed properly on your project

The package lets you generate TypeScript interfaces from your Laravel models.

Laravel TypeScript The package lets you generate TypeScript interfaces from your Laravel models. Introduction Say you have a model which has several p

This Package helps you in laravel application to log all desired activity for each request from request entry point to generate response at a single snapshot.

Laravel Scenario Logger This Package helps you in laravel application to log all desired activity for each request from request entry point to generat

A laravel package to generate class files from stub files.

Laravel Stub Generator A php laravel package to generate useable php files from given stub files . Installation Require the package using composer: co

Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords.

Laravel Otpify 🔑 Introduction Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords. Install

Releases(1.1.0)
Owner
Touhidur Rahman
Husband, father, big time documentary tv series lover and software engineer . Passionate about PHP, Laravel, Ruby on Rails, Vue.js and C/C++ . Learning Rust .
Touhidur Rahman
Add a progress bar column to your Filament tables.

Add a progress bar column to your Filament tables. This package provides a ProgessColumn that can be used to display a progress bar in a Filament tabl

Ryan Chandler 22 Nov 12, 2022
A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Touhidur Rahman 17 Jan 20, 2022
This package provides a trait that will generate a unique uuid when saving any Eloquent model.

Generate slugs when saving Eloquent models This package provides a trait that will generate a unique uuid when saving any Eloquent model. $model = new

Abdul Kudus 2 Oct 14, 2021
A laravel package to handle sanitize process of model data to create/update model records.

Laravel Model UUID A simple package to sanitize model data to create/update table records. Installation Require the package using composer: composer r

null 66 Sep 19, 2022
Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Jameson Lopp 28 Dec 19, 2022
Generate trends for your models. Easily generate charts or reports.

Laravel Trend Generate trends for your models. Easily generate charts or reports. Support us Like our work? You can support us by purchasing one of ou

Flowframe 139 Dec 27, 2022
Automatically generate ERD Diagrams from Model's relations in Laravel

Laravel ERD Generator Automatically generate interactive ERD from Models relationships in Laravel. This package provides a CLI to automatically genera

Pulkit Kathuria 90 Dec 29, 2022
Generate UUID for a Laravel Eloquent model attribute

Generate a UUIDv4 for the primary key or any other attribute on an Eloquent model.

Alex Bouma 4 Mar 1, 2022
A simple laravel package to handle multiple key based model route binding

Laravel Model UUID A simple package to handle the multiple key/column based route model binding for laravel package Installation Require the package u

null 13 Mar 2, 2022
A simple Laravel event log package for easy model based logging.

Karacraft Logman A simple Model Event Logging Package Usage Installation composer require karacraft/logman Migrate php artisan migrate Publish php a

Karacraft 0 Dec 28, 2021