LoginSignup
0
0

More than 1 year has passed since last update.

laravelで短いUUIDをprimaryキーとして設定する。

Posted at

ライブラリインストール。下記の二つ。

composer require goldspecdigital/laravel-eloquent-uuid //これはバージョンによって変える。
composer require pascaldevink/shortuuid

マイグレーションの変更

usersテーブルのマイグレーション
//$table->id();
$table->uuid('id')->primary();

モデルファイルの継承元の変更

Userモデルは下記のように。

User.php
//use Illuminate\Foundation\Auth\User as Authenticatable;
use GoldSpecDigital\LaravelEloquentUUID\Foundation\Auth\User as Authenticatable;

それ以外は下記のように変更。

Userモデル以外。
use GoldSpecDigital\LaravelEloquentUUID\Database\Eloquent\Model;

ちなみに下記が便利コマンド。

これでUUID用のモデルが作られる。
php artisan uuid:make:model [モデル名]

下記のように書けば作成時にuuidが設定される。

コントローラー
use GoldSpecDigital\LaravelEloquentUUID\Database\Eloquent\Model;
use Illuminate\Support\Str;
use PascalDeVink\ShortUuid\ShortUuid;

 public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        // newした時に自動的にuuidを設定する。
        $uuid4 = Str::uuid();
        $shortuuid = new ShortUuid();
        $su_string = $shortuuid->encode($uuid4);

        $this->attributes['id'] = $su_string;
    }
0
0
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
0
0