PHP code example of swiss-devjoy / laravel-easy-hashids

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

    

swiss-devjoy / laravel-easy-hashids example snippets


return [
    'default' => [
        // Generate a unique alphabet here: https://sqids.org/playground
        'alphabet' => env('HASHID_DEFAULT_ALPHABET', 'VCzODgjZNMFaXTfqnhLp84EtHlk7RmiWrScBoPIwK2QGxs1ed35UJ6yAYb0v9u'),
        'min_length' => env('HASHID_DEFAULT_MIN_LENGTH', 10),
    ],

    'models' => [
        // App\Models\YourModel::class => [
        //     'alphabet' => 'kwevdSQOEiT349X5atVrLozGHFWYp87uAUlc0mbPNIJKf1qMshCyg2BD6ZxnjR',
        //     'min_length' => 10,
        // ],
    ],
];

use SwissDevjoy\LaravelEasyHashids\HasHashid;
use SwissDevjoy\LaravelEasyHashids\HashidRouting;

class Product extends Model
{
    use HasHashid;
    use HashidRouting;
}

$product = Product::find(1);
echo $product->hashid; // Returns something like "2tFub5I1ge"

Route::get('/products/{product}', function (Product $product) {
    return view('products.show', compact('product'));
})->name('products.product');

// Generates a URL with the hashid that looks sth like /products/2tFub5I1ge
route('products.show', ['product' => $product]);

return [
    'default' => [
        // Generate a unique alphabet here: https://sqids.org/playground
        'alphabet' => env('HASHID_DEFAULT_ALPHABET', 'VCzODgjZNMFaXTfqnhLp84EtHlk7RmiWrScBoPIwK2QGxs1ed35UJ6yAYb0v9u'),
        'min_length' => env('HASHID_DEFAULT_MIN_LENGTH', 10),
    ],

    'models' => [
        // App\Models\YourModel::class => [
        //     'alphabet' => 'kwevdSQOEiT349X5atVrLozGHFWYp87uAUlc0mbPNIJKf1qMshCyg2BD6ZxnjR',
        //     'min_length' => 10,
        // ],
    ],
];

class BookComponent extends Component
{
    public Book $book;

    public function render()
    {
        return view('components.book');
    }
}

$book = Book::make();

// Convert ID to hashid
$hashid = $book->idToHashid(10);

// Convert hashid back to ID
$id = $book->hashidToId('2tFub5I1ge');

// Author model (uses HasHashid)
$author = Author::findByHashidOrFail('uwe14hrgh');

// Book model (uses HasHashid)
$book = $author->books()->findByHashid('2tFub5I1ge');

'models' => [
    App\Models\Book::class => [
        'alphabet' => 'xyz123ABC789DEFGHIJKLMNOPQRSTUVWdefghijklmnopqrstuvwab456XYZ',
        'min_length' => 12,
    ],
],
bash
php artisan vendor:publish --tag="laravel-easy-hashids-config"