PHP code example of bretterer / laravel-hashid

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

    

bretterer / laravel-hashid example snippets


use Bretterer\LaravelHashId\Traits\HasHashIds;

class User extends Model
{
	use HasHashIds;
	// ...
}

Schema::create('users', function ($table) {
	$table->hashId('id', 16)->primary();
	$table->string('name');
});

Schema::create('posts', function ($table) {
	$table->hashId('id', 16)->primary();
	$table->foreignHashId('user_id', 'users', 'id', 16);
	$table->string('title');
});

$user = User::create(['name' => 'Alice']);
echo $user->id; // 16-character base62 HashId

$post = Post::create(['user_id' => $user->id, 'title' => 'Hello']);

class PrefixedUser extends Model {
	use HasHashIds;
	public function idPrefix(): string { return 'usr'; }
}

$user = PrefixedUser::create(['name' => 'Dave']);
echo $user->id; // usr_XXXXXXXXXXXXXXX

use Bretterer\LaravelHashId\LaravelHashId;

$generator = new LaravelHashId();
$hashId = $generator->generate(16); // Random HashId
$hashIdFromValue = $generator->generateFromValue('value', 'salt', 16); // HashId from value