Skip to content

leMaur/laravel-human-id

Repository files navigation

Laravel Human IDs

Latest Version on Packagist Total Downloads License Tests GitHub Sponsors Trees

This package has been inspired by the article "Designing APIs for humans: Object IDs"
appeared on Dev (Aug 30, 2022 / by Paul Asjes).

I really like the approach Stripe uses to define the object ID, so I figured out how to make something similar for Laravel.
Basically, the package generate a so-called "human id" by prepending a prefix to a ULID with a separator between them.

An example should be better than a thousand words...

👇 the structure -----------------

{prefix}{separator}{ulid}


👇 the params --------------------

prefix: post
separator: _
ulid: 26 alphanumeric characters


👇 the result --------------------

post_01h554vp2prg6zfayagh83ccx7

Support Me

Hey folks,

Do you like this package? Do you find it useful, and it fits well in your project?

I am glad to help you, and I would be so grateful if you considered supporting my work.

You can even choose 😃:


Installation

You can install the package via composer:

composer require lemaur/laravel-human-id

Usage

  1. Add the "human ID" field in your migration files.
  2. Import the Lemaur\HumanId\Concerns\HasHuids trait into your eloquent model.

Here's a real-life example of how to implement the trait on a model.

// database\migrations\create_posts_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('posts', static function (Blueprint $table) {
            $table->id();
            
            $table->huid(); // <-- declare "huid" field
            
            // other fields...
        });
    }
}
// app\Models\Post.php

namespace App\Models;

use \Illuminate\Database\Eloquent\Model;
use \Lemaur\HumanId\Concerns\HasHuids;

class Post extends Model
{
    use HasHuids; // <-- import trait
    
    /** @var string */
    private const HUID_PREFIX = 'post'; // <-- declare prefix (max 4 characters)
}

// this will generate a huid like --> post_01h554vp2prg6zfayagh83ccx7

Configuration

You can use a different name for the field (currently is huid) and a different separator (currently is _).
To do that, you should publish the configuration file (config/human-id.php) and change them from there.

php artisan vendor:publish --tag=human-id-config

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.