coderscantina/hashidable

An adapted bridge for using hashids in Laravel models.

v1.0.2 2023-05-23 15:59 UTC

This package is auto-updated.

Last update: 2024-04-23 17:52:23 UTC


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