Generator unique identity 64 bits and combine with laravel eloquent.
This project inspires from the article Sharding & IDs at Instagram. With it, you can create uid for your table:
- 64-bits length.
- sortable by time.
Require this package with composer using the following command:
composer require reishou/unique-identity
Laravel uses Package Auto-Discovery, so doesn't require you to manually add the ServiceProvider.
Publish the config file with:
php artisan vendor:publish --provider="Reishou\UniqueIdentity\UidServiceProvider"
You can change entity_table
name in config/uid.php
(default entity_sequences
).
Then run command generate migration:
php artisan uid:table
After the migration has been generated you can create the entity_table
by running:
php artisan migrate
Your Eloquent models should use the Reishou\UniqueIdentity\HasUid
trait.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Reishou\UniqueIdentity\HasUid;
class YourModel extends Model
{
use HasUid;
}
The primaryKey
will be filled auto by uid generator when model created or saved for the first time.
// instantiate a new model
$model = new YourModel();
// set attributes on the model
$model->field = $value;
// save model
$model->save();
// or use the create method to "save" a new model
YourModel::create($attributes)
You can generate multi uid for multi record before inserting to database.
// $listAttributes contain 10 elements, every element is an array attributes will insert to database.
$listAttributes = [...];
// array $ids contains 10 uid
$ids = YourModel::uid(count($listAttributes));
// set ids to attributes
$listAttributes = collect($listAttributes)->map(function ($attributes, $index) use ($ids) {
$attributes['id'] = $ids[$index];
$attributes['created_at'] = now();
$attributes['updated_at'] = now();
return $attributes;
})
->toArray();
// insert to database
YourModel::insert($listAttributes);
The MIT License (MIT). Please see LICENSE for more information.
Please see CHANGELOG for more information on what has changed recently.