A package to use human readable keys in your Laravel models. Inspired by Stripe's id generation procedures.
Enables you to have KSUID keys in your models, which are human readable and sortable.
Example:
pos_2JvL8Gv5mirjbIVAlSRFrC8EaWRforModels/Post.phpusr_p6UEyCc8D8ecLijAI5zVwOTP3D0forModels/User.php
You can install the package via composer:
composer require oneduo/laravel-human-keysYou can publish the config file with:
php artisan vendor:publish --tag="human-keys-config"This is the contents of the published config file:
return [
/*
|--------------------------------------------------------------------------
| Generator
|--------------------------------------------------------------------------
|
| Used to define the generator to use for generating model keys.
|
| Supported:
| - ksuid (abc_p6UEyCc8D8ecLijAI5zVwOTP3D0)
| - snowflake (abc_1537200202186752)
|
| Default: ksuid
|
| Note: You may define your own generator by implementing the contract
| Oneduo\LaravelHumanKeys\Contracts\Generator and passing
| the class name to the generator config option.
|
| See the example below:
| 'generator' => \App\Services\MyGenerator::class
*/
'generator' => 'ksuid',
];To get started, use the HasHumanKey trait in your model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Oneduo\LaravelHumanKeys\Concerns\HasHumanKey;
class Post extends Model
{
use HasHumanKey;
}When using the ksuid generator, the generated key will something like this: pos_2JvL8Gv5mirjbIVAlSRFrC8EaWR
When using the snowflake generator, the generated key will something like this: pos_451734027389370636
You may set your own key prefix for each model by implementing the following method:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Oneduo\LaravelHumanKeys\Concerns\HasHumanKey;
class Post extends Model
{
use HasHumanKey;
public static function getKeyPrefix() : string {
// prefix without _ underscore as it gets added by the generator
return 'post_prefix'
}
}composer testPlease see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.