PHP code example of cirlmcesc / laravel-hashids

1. Go to this page and download the library: Download cirlmcesc/laravel-hashids 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/ */

    

cirlmcesc / laravel-hashids example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Cirlmcesc\LaravelHashids\Traits\Hashidsable;

class Foo extends Model
{
    use Hashidsable;

    /**
     * Encrypt the list of other fields that 
     * need to be encrypted while encrypting the ID.
     *
     * @var bool
     */
    public $_only_encode_id = false;

    /**
     * When encrypting an ID, you can choose to
     * Only encrypt which fields.
     * You can also set some fields with suffixes 
     * other than `_id`, but they must be of type `int`.
     *
     * @var array<string>
     */
    public $_only_need_encode_fields = [
        'aaa',
        'bbb',
        'ccc_id',
        'ddd_id',
    ];

    /**
     * While encrypting the ID, you can choose 
     * which fields do not encryption,
     * Only applicable to fields with suffix 'id'.
     *
     * @var array<string>
     */
    public $_doesnt_need_encode_fields = [
        'xxx_id',
        'yyy_id',
        'zzz_id',
    ];
}



use Illuminate\Support\Facades\Route;
use App\Models\Foo;

Route::get('/foos/{foo}', fn(Foo $foo) => $foo);




namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class FooResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return hashids_encode_in_array([
            'id' => $this->id,
            'foo' => $this->foo,
            'app_id' => $this->app_id,
            'banana_id' => $this->banana_id,
        ]);
    }
}




/**
 * encode id
 *
 * @param int $id
 * @return string
 */
function hashids_encode(int $id): string;

/**
 *  decode id
 *
 * @param string $id
 * @param int $remedy 
 * @return int
 */
function hashids_decode(string $id, int $remedy = 0): int;

 /**
 * encode ids in array
 *
 * @param array $data
 * @param array $dosent_encode_keys
 * @param string $suffix
 * @return array
 */
function hashids_encode_in_array(array $data, array $dosent_encode_keys = [], string $suffix = '_id'): array;

/**
 * decode ids in array
 *
 * @param array $data
 * @param array $dosent_decode_keys
 * @param string $suffix
 * @return array
 */
function hashids_decode_in_array(array $data, array $dosent_decode_keys = [], string $suffix = '_id'): array;

shell
php artisan hashids:install
hashids_encode_in_array
shell
php artisan hashids:test