ライブラリインストール。下記の二つ。
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;
}