Skip to content

An adapted bridge for using laravel-hashids in Laravel models.

License

Notifications You must be signed in to change notification settings

coderscantina/hashidable

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Hashidable from Coder's Cantina

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

About

An adapted bridge for using laravel-hashids in Laravel models.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages