Laravel 5.5
webpatser/laravel-uuid 3.0
を使用します。
ライブラリをインストール
UUIDの生成は「webpatser/laravel-uuid」というライブラリがありますので、こちらを使用します。
webpatser/laravel-uuid
下記コマンドでインストールしましょう。
$ composer require webpatser/laravel-uuid
Laravel 5.4以下ならapp.phpのaliasesに登録します。
config/app.php
'aliases' => [ // ・・・ 'Uuid' => Webpatser\Uuid\Uuid::class, ],
マイグレーション
マイグレーションファイルのスキーマ設定でidのincrementsをuuidに変更します。
primaryにidを指定します。
例えばpostsテーブルを作成した場合は下記のようにします。
database/migrations/xxxxxxxx_create_posts_table.php
Schema::create('posts', function (Blueprint $table) {
$table->uuid('id');
$table->string('title');
$table->text('body');
$table->timestamps();
$table->primary('id');
});
モデルの設定
最後にモデルにUUIDを生成する処理をboot設定します。
それと連番ではないので、incrementingをfalseにします。
app/Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Webpatser\Uuid\Uuid;
class Post extends Model
{
public $incrementing = false;
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = Uuid::generate()->string;
});
}
}
以上で、UUIDで保存してくれます。

