PHP code example of veelasky / laravel-hashid

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

    

veelasky / laravel-hashid example snippets


use Illuminate\Database\Eloquent\Model;
use Veelasky\LaravelHashId\Eloquent\HashableId;

class User extends Model {
    use HashableId;
    ...
}


$user = User::find(1);     // instance of user.
$user->hash;               // generate HashId.

// Database operation

// get user by hashed id.
$user = User::byHash($hash);

// get user by hashed id, and throw ModelNotFoundException if not present.
$user = User::byHashOrFail($hash);

// get hashed id from the primary key.
User::idToHash($id);

// get ID from hashed string.
User::hashToId($hash);

 // query scope with `byHash` method.
User::query()->byHash($hash);

class User extends Model {
    use HashableId;

    // add this property to your model if you want to persist to the database.
    protected $shouldHashPersist = true;

    // by default, the persisted value will be stored in `hashid` column
    // override column name to your desired name.
    protected $hashColumnName = 'hashid';
    ...
}


use App\Models\User;

class UserController extends Controller
{
    /**
     * Route /users/{user}
     * Ex: GET /users/k1jTdv6l
     */
    public function show(User $user)
    {
        ...
    }
}

// using facade.
HashId::hashToId($hash, User::class)      // same as User::hashToId($hash);
HashId::idToHash($id, User::class)        // same as User::idToHash($hash);

// HashId facade class is an implementation of \Veelasky\Laravel\HashId\Repository

HashId::make($key, $salt);              // will return \HashId\HashId class.

// once you instantiated the object, you can retrieve it on your next operation
HashId::get($key);

class User extends Model {
    protected $hashKey = 'somethingUnique';
}

class Customer extends User {

}

$customer = Customer::find(1);
$user = User::find(1);

$user->hash; // will be equal to $customer->hash

use App\Models\User;
use Veelasky\LaravelHashId\Rules\ExistsByHash;

...
Validator::make([
    'id' => $hashedId
], [
    'id' => ['
bash
php artisan vendor:publish --tag=laravel-hashid-config