An adapted bridge for using laravel-hashids in Laravel models.
- Hashid route model binding
- Individual salt per model
- Optional individual configuration per model
- Helper methods for encoding, decoding and finding by hashid
Install the package via composer using this command:
composer require coderscantina/hashidable
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