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
- Collection support for working with multiple hashids
- Performance optimizations with factory caching
Install the package via composer using this command:
composer require coderscantina/hashidableAdd the Hashidable trait to your model
use CodersCantina\Hashidable;
class Foo extends Model
{
use Hashidable;
}Expose the hashid in a resource
class FooResource 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\Foo $foo
* @return \Illuminate\Http\Response
*/
public function show(Foo $foo)
{
return new FooResource($foo);
}Static methods to work with hashIds:
Foo::encodeHashId(1); // Convert ID to hashid
Foo::decodeHashId('A3'); // Convert hashid to ID
Foo::findByHashId('A3'); // Find model by hashid
Foo::findByHashIdOrFail('A3'); // Find model by hashid or throw exceptionMethods for working with multiple models or IDs:
// Encode multiple IDs
Foo::encodeHashIds([1, 2, 3]); // Returns array of hashids
// Decode multiple hashids
Foo::decodeHashIds(['A3', 'B7']); // Returns array of IDs
// Find multiple models by hashids
Foo::findByHashIds(['A3', 'B7']); // Returns collection of modelsOverwrite 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