在 Laravel 5.7 使用 UUID 做為資料庫主鍵

環境

  • Windows 10
  • Homestead

安裝套件

安裝 spatie/laravel-binary-uuid 套件。

1
composer require spatie/laravel-binary-uuid

修改遷移

users 遷移檔為例:

1
2
3
4
5
6
7
8
9
10
Schema::create('users', function (Blueprint $table) {
$table->uuid('uuid');
$table->primary('uuid');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});

修改模型

User 模型為例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php

namespace App;

use Spatie\BinaryUuid\HasBinaryUuid; // 調用特徵機制
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
use Notifiable;
use HasBinaryUuid; // 使用特徵機制

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];

/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}

參考資料