maxsky/laravel-snowflake

Snowflake for Laravel/Lumen.

v1.2.1 2019-07-02 17:56 UTC

This package is auto-updated.

Last update: 2024-04-29 04:03:25 UTC


README

Build Status Latest Stable Version License 68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c696e6b2d3939362e6963752d7265642e737667

This Laravel/Lumen package to generate 64 bit identifier like the snowflake within Twitter.

Installation

composer require "maxsky/laravel-snowflake"

# Just used with Laravel
php artisan vendor:publish --provider="Snowflake\SnowflakeServiceProvider"

Configuration

If config/snowflake.php not exist, run below:

# Just Laravel
php artisan vendor:publish

If used Lumen framework, please copy vendor/maxsky/laravel-snowflake/config/snowflake.php file to config folder.

And then add some environment config in .env file (if you used):

SNOWFLAKE_EPOCH='2019-05-01 00:00:00'
SNOWFLAKE_WORKER_ID=1
SNOWFLAKE_DATACENTER_ID=1

Usage

Get instance

$snowflake = app('Snowflake\Snowflake');

Generate snowflake identifier

$id = $snowflake->next();

Usage with Eloquent

Add the Snowflake\HasSnowflakePrimary trait to your Eloquent model. This trait make type snowflake of primary key. Don't forget to set the Auto increment property to false.

<?php

namespace App;

use Snowflake\HasSnowflakePrimary;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable {

    use HasSnowflakePrimary, Notifiable;

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;
}

Finally, in migrations, set the primary key to bigInteger and primary.

/**
 * Run the migrations.
 *
 * @return void
 */
public function up() {
    Schema::create('users', function (Blueprint $table) {
        // $table->increments('id');
        $table->bigInteger('id')->primary();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

License

MIT License From Kra8.