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
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 😃:
- You can sponsor me 😎 with a monthly subscription.
- You can buy me a coffee ☕ or a pizza 🍕 just for this package.
- You can plant trees 🌴. By using this link we will both receive 30 trees for free and the planet (and me) will thank you.
- You can "Star ⭐" this repository (it's free 😉).
You can install the package via composer:
composer require lemaur/laravel-human-id
- Add the "human ID" field in your migration files.
- 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
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
composer test
Please 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.