LoginSignup
7
10

More than 3 years have passed since last update.

Laravel8でUUIDを使用してみるよ【簡単】

Posted at

UUIDを使う方法をサクッと書いていきます。

ライブラリインストール

composer require goldspecdigital/laravel-eloquent-uuid:^8.0

マイグレーション


    public function up()
    {
        Schema::create('article_drafts', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            //以下は好きなものを書きましょう。
        });
    }

ちなみにUUIDをプライマリキーにする人もいますが、外部キーとして使用することもある場合は、別にUUID用のカラムを作った方が良きです。

リレーれション先でも128ビットの数値をデータとして持っておくのは非効率ですからね。

UUIDの生成(データの保存)

あとは下記のように保存したい時に記述してあげればOK。


use Illuminate\Support\Str;

//省略

'uuid'=>(string) Str::uuid(),

idを隠す

ついでにidは隠しておくと良きです。

class Article extends Model
{
    protected $fillable = [
        'uuid',//お好きなように
    ];

    protected $hidden = [
        'id' //こんな感じ。
    ];
}

これで、idが隠れます。

7
10
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
7
10