LoginSignup
2
2

More than 1 year has passed since last update.

Laravelでidをuuidへ変更する

Last updated at Posted at 2022-08-29

はじめに

Laravelでidをuuidへ変更する際のメモです。
この記事は「プログラミング初学者」を対象にしています。

ライブラリをインストール

example.php
composer require goldspecdigital/laravel-eloquent-uuid:^8.0

※laravelのバージョンに合わせてバージョンを適宜変更

マイグレーションファイル

example.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('users', function (Blueprint $table) {
      $table->uuid('id')->primary(); //変更箇所
      $table->string('email')->unique();
      $table->timestamp('email_verified_at')->nullable();
      $table->string('password');
      $table->rememberToken();
      $table->timestamps();
    });
  }
}

テストデータ挿入

example.php
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class UserSeeder extends Seeder
{
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run()
  {
    DB::table('users')->insert([
      [
        'id' => (string)Str::uuid(), //uuidを使用
        'email' => 'test@example.com',
        'password' => Hash::make(env('GUEST_PASSWORD')),
        'created_at' => '2022/08/07 14:09:10'
      ],
    ]);
  }
}

Seederを実行

example.php
php artisan db:seed

もしくは、マイグレーションごと巻き戻したい場合↓

example.php
php artisan migrate:refresh --seed

自動でUUIDをセットする方法

example.php
<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Str;

class User extends Authenticatable
{
  //ここから追記
  protected static function booted()
  {
    static::creating(function (User $model) {
      empty($model->id) && $model->id = Str::uuid();
    });
  }
}

上記のstaticメソッドを記述することで、自動的にuuidが作成されて保存されます。

2
2
1

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