Skip to content
This repository has been archived by the owner on Jun 3, 2023. It is now read-only.
/ unique-identity Public archive

Generator unique identity 64 bits and combine with laravel eloquent.

License

Notifications You must be signed in to change notification settings

reishou/unique-identity

Repository files navigation

unique-identity

Generator unique identity 64 bits and combine with laravel eloquent.

Latest Version on Packagist Software License Build Status Total Downloads

Overview

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.

Installation

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

Usage

Automatic when eloquent boot creating

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)

Manual generate list uid

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);

License

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

Changelog

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

About

Generator unique identity 64 bits and combine with laravel eloquent.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages