LoginSignup
8
3

More than 3 years have passed since last update.

Laravel 5.8 primaryKeyをint(AUTO_INCREMENT)からUUIDに変える

Posted at

外部ライブラリを使う

webpatser/laravel-uuid

$ 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',
        ]);
8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3