Skip to content

Create HasSnowflakePrimary Trait

Pre-release
Pre-release
Compare
Choose a tag to compare
@kra8 kra8 released this 16 Oct 13:17

Update v1.1.0

  • Add HasSnowflakePrimary trait.

Feature

$user = new User();
$user->name = 'example';
$user->email = '[email protected]';
$user->password = '123456789';
$user->save();

echo $user->id; // snowflake id(1282679165292544)

Usage

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 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();
    });
}