coderscantina / hashidable
An adapted bridge for using hashids in Laravel models.
Installs: 4 097
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: ~7.3||^8.0
- illuminate/support: ^8.0||^9.0||^10.0||^11.0
- vinkla/hashids: ~9.1||~10.0||^11.0
Requires (Dev)
- graham-campbell/testbench: ^5.4||^6.0
- illuminate/database: ^8.0||^9.0||^10.0||^11.0
- mockery/mockery: ^1.3
- phpunit/phpunit: ^9.3
README
An adapted bridge for using laravel-hashids in Laravel models.
Features
- Hashid route model binding
- Individual salt per model
- Optional individual configuration per model
- Helper methods for encoding, decoding and finding by hashid
🏗 Install
Install the package via composer using this command:
composer require coderscantina/hashidable
⚙️ Usage
Add the Hashidable trait to your model
use CodersCantina\Hashidable; class Phone extends Model { use Hashidable; }
Expose the hashid in a resource
class PhoneResource extends JsonResource { /** * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->getRouteKey(), ]; } }
Resolve the model via hashid in a controller
/** * @param \App\Models\Phone $phone * @return \Illuminate\Http\Response */ public function show(Phone $phone) { return new PhoneResource($phone); }
Static methods to work with hashIds:
Foo::encodeHashId(1); Foo::decodeHashId('A3'); Foo::findByHashId('A3');
Overwrite config with a model like App\User::class
# config/hashids.php 'connections' => [ 'main' => [ 'salt' => env('HASHIDS_SALT'), 'length' => 8, 'alphabet' => '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', ], \App\User::class => [ 'salt' => env('HASHIDS_SALT'), 'length' => 5, 'alphabet' => '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', ], ],
See for more information Route Model Binding