1. Go to this page and download the library: Download bvtterfly/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/ */
bvtterfly / laravel-hashids example snippets
return [
/*
|--------------------------------------------------------------------------
| Default Salt
|--------------------------------------------------------------------------
|
| This is the salt that uses by Hashids package to generate unique id.
|
*/
'salt' => config('app.name')
];
namespace App\Models;
use Bvtterfly\LaravelHashids\HasHashId;
use Bvtterfly\LaravelHashids\HashIdOptions;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasHashId;
public function getHashIdOptions(): HashIdOptions
{
return HashIdOptions::create()->saveHashIdTo('hashid');
}
}
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('hashid')->nullable(); // Field name same as your `saveHashIdTo`
//...
$table->timestamps();
});
}
}
public function getHashIdOptions(): HashIdOptions
{
return HashIdOptions::create()
->saveHashIdTo('hashid')
->setType('hex') // default = int
;
}
public function getHashIdOptions(): HashIdOptions
{
return HashIdOptions::create()
->saveHashIdTo('hashid')
->generateHashIdFrom('custom_key')
;
}
public function getHashIdOptions(): HashIdOptions
{
return HashIdOptions::create()
->saveHashIdTo('hashid')
->setAutoGeneratedField(false)
;
}
public function getHashIdOptions(): HashIdOptions
{
return HashIdOptions::create()
->saveHashIdTo('hashid')
->setGenerateUniqueHashIds(false)
;
}
public function getHashIdOptions(): HashIdOptions
{
return HashIdOptions::create()
->saveHashIdTo('hashid')
->setMinimumHashLength(10)
;
}
public function getHashIdOptions(): HashIdOptions
{
return HashIdOptions::create()
->saveHashIdTo('hashid')
// use all lowercase alphabet instead of 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
->setAlphabet('abcdefghijklmnopqrstuvwxyz')
;
}
use App\Models\Post;
Route::get('/posts/{post:hashid}', function (Post $post) {
return $post;
});
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'hashid';
}