外部ライブラリを使う
$ composer require webpatser/laravel-uuid
Str::orderedUuidを使う(Laravel 5.6+)
Laravelのヘルパ関数だが外部ライブラリmoontoast/math
が必要
$ composer require moontoast/math
idの型を変える
こちらを参考に
[Laravel] テーブルのプライマリキーにuuidを使う
databases/migrations/XXX_users_table.php
- $table->bigIncrements('id');
+ $table->uuid('id'); // string('id', 36)と同じ
+ $table->primary('id');
モデルを修正
プライマリキーの名称を変える場合は、プロパティ$primaryKey
で設定
型がデフォルトでintかつautoincrementのため、以下の定義を追加
app/User.php
protected $primaryKey = 'hoge_id' // 任意設定
public $incrementing = false; // AUTO_INCREMENT不可
protected $keyType = 'string'; // int -> string
レコード作成時にidを自動生成する処理を追加する。useを忘れないように。
app/User.php
// webpatserの場合
use Illuminate\Database\Eloquent\Model;
use Webpatser\Uuid\Uuid;
// Str::orderedUuidの場合
use Illuminate\Support\Str;
(略)
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
// webpatserの場合
$model->{$model->getKeyName()} = (string) Uuid::generate()->string;
// Str::orderedUuidの場合
$model->{$model->getKeyName()} = (string) Str::orderedUuid();
});
}
Seeder経由で追加する場合
そのままではINSERTで失敗するのでidも自前で定義する
databases/seeders/UserTableSeeder.php
DB::table('users')->insert([
+ 'id' => (string) Str::orderedUuid(),
'name' => 'admin',
]);