kra8 / laravel-snowflake by kra8

Snowflake for Laravel and Lumen.
236,573
155
3
Package Data
Maintainer Username: kra8
Maintainer Contact: koki@asai.email (Koki Asai)
Package Create Date: 2017-10-14
Package Last Update: 2024-11-06
Home Page:
Language: PHP
License: MIT
Last Refreshed: 2024-11-15 03:03:26
Package Statistics
Total Downloads: 236,573
Monthly Downloads: 6,923
Daily Downloads: 329
Total Stars: 155
Total Watchers: 3
Total Forks: 18
Total Open Issues: 4

Laravel Snowflake

Build Status Latest Stable Version License

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

Laravel Installation

composer require "kra8/laravel-snowflake"

php artisan vendor:publish --provider="Kra8\Snowflake\Providers\LaravelServiceProvider"

Lumen Installation

  • Install via composer
composer require "kra8/laravel-snowflake"
  • Bootstrap file changes Add the following snippet to the bootstrap/app.php file under the providers section as follows:
// Add this line
$app->register(Kra8\Snowflake\Providers\LumenServiceProvider::class);

Usage

Get instance

$snowflake = $this->app->make('Kra8\Snowflake\Snowflake');

or

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

Generate snowflake identifier

$id = $snowflake->next();

Usage with Eloquent

Add the Kra8\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 Kra8\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, unsigned and primary.

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

Configuration

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

php artisan vendor:publish

Licence

MIT licence