kra8 / laravel-snowflake by kra8

Snowflake for Laravel and Lumen.
191,942
137
2
Package Data
Maintainer Username: kra8
Maintainer Contact: koki@asai.email (Koki Asai)
Package Create Date: 2017-10-14
Package Last Update: 2024-03-15
Home Page:
Language: PHP
License: MIT
Last Refreshed: 2024-04-26 03:01:38
Package Statistics
Total Downloads: 191,942
Monthly Downloads: 5,694
Daily Downloads: 275
Total Stars: 137
Total Watchers: 2
Total Forks: 17
Total Open Issues: 1

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