maxsky / laravel-snowflake
Snowflake for Laravel/Lumen.
v1.2.1
2019-07-02 17:56 UTC
Requires
- php: >=7.0.0
Requires (Dev)
- orchestra/testbench: ^3.5
This package is auto-updated.
Last update: 2024-10-29 05:34:39 UTC
README
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.