PHP code example of coderscantina / hashidable

1. Go to this page and download the library: Download coderscantina/hashidable library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

coderscantina / hashidable example snippets


use CodersCantina\Hashidable;

class Foo extends Model
{
    use Hashidable;
}

class FooResource extends JsonResource
{
    /**
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->getRouteKey(),
        ];
    }
}

/**
* @param  \App\Models\Foo  $foo
* @return \Illuminate\Http\Response
*/
public function show(Foo $foo)
{
    return new FooResource($foo);
}

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 exception

// 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 models

# config/hashids.php

'connections' => [

    'main' => [
        'salt' => env('HASHIDS_SALT'),
        'length' => 8,
        'alphabet' => '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    ],

    \App\User::class => [
        'salt' => env('HASHIDS_SALT'),
        'length' => 5,
        'alphabet' => '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    ],

],