Laravel OptiKey
Use UUID or Ulid as optional or primary key in Laravel.
composer require riipandi/laravel-optikey
This package adds a very simple trait to automatically generate a UUID or Ulid for your Models.
Quick Start
Update your schemas
First, you need to add uuid or ulid column in your migration. For example:
php artisan make:migration AddUuidColumnToUsersTable
In this case you will use UUID as secondary key:
$table->uuid('uuid')->after('id')->unique()->index();
In this case you will use UUID as primary key:
$table->uuid('id')->primary();
Sample migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddUlidColumnToUsersTable extends Migration
{
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('ulid', 26)->unique()->index()->after('id');
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('ulid');
});
}
}
Using UUID
Add the "\Riipandi\LaravelOptiKey\Traits\HasUuidKey;" trait to your model:
<?php
namespace App;
use Riipandi\LaravelOptiKey\Traits\HasUuidKey;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasUuidKey;
}
If your column name is not "uuid", simply add a new property to your model named "optiKeyFieldName":
protected $optiKeyFieldName = 'unique_id';
This trait also adds a scope:
\App\User::byUuid('uuid')->first();
And static find method:
\App\User::findByUuid('uuid')
A second trait is available if you use your UUIDs as primary keys:
<?php
namespace App;
use Riipandi\LaravelOptiKey\Traits\HasUuidKey;
use Riipandi\LaravelOptiKey\Traits\UuidAsPrimaryKey;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasUuidKey, UuidAsPrimaryKey;
}
Using Ulid
Add the "\Riipandi\LaravelOptiKey\Traits\HasUlidKey;" trait to your model:
<?php
namespace App;
use Riipandi\LaravelOptiKey\Traits\HasUlidKey;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasUlidKey;
}
If your column name is not "ulid", simply add a new property to your model named "optiKeyFieldName":
protected $optiKeyFieldName = 'unique_id';
This trait also adds a scope:
\App\User::byUlid('ulid')->first();
And static find method:
\App\User::findByUlid('ulid')
A second trait is available if you use your Ulids as primary keys:
<?php
namespace App;
use Riipandi\LaravelOptiKey\Traits\HasUlidKey;
use Riipandi\LaravelOptiKey\Traits\UlidAsPrimaryKey;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasUlidKey, UlidAsPrimaryKey;
}
It simply tells Laravel that your primary key isn't an auto-incrementing integer, so it will treat the value correctly.
Copyright
This project is licensed under MIT: https://aris.mit-license.org/
Copyrights in this project are retained by their contributors. No copyright assignment is required to contribute to this project. Please see license file for more information.