This Laravel/Lumen package to generate 64 bit identifier like the snowflake within Twitter.
composer require "maxsky/laravel-snowflake"
# Just used with Laravel
php artisan vendor:publish --provider="Snowflake\SnowflakeServiceProvider"
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
Get instance
$snowflake = app('Snowflake\Snowflake');
Generate snowflake identifier
$id = $snowflake->next();
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();
});
}
MIT License From Kra8.