Skip to content

Use Stripe-like keys for your models, configurable and extendable

License

Notifications You must be signed in to change notification settings

oneduo/laravel-human-keys

Repository files navigation

Laravel Human Keys

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

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_2JvL8Gv5mirjbIVAlSRFrC8EaWR for Models/Post.php
  • usr_p6UEyCc8D8ecLijAI5zVwOTP3D0 for Models/User.php

Table of Contents

Installation

You can install the package via composer:

composer require oneduo/laravel-human-keys

You 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',
];

Usage

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

Overriding the key prefix

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'
    }
}

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.