# Laravel Factory 使用 faker ###### tags: Laravel 原本規劃收件地址 (UserAddress) 的 Migration 中縣市跟區是分兩個欄位 (city, district) ``` public function up() { Schema::create('user_addresses', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->string('city'); $table->string('district'); $table->string('address'); $table->unsignedInteger('zip'); $table->string('contact_name'); $table->string('contact_phone'); $table->dateTime('last_used_at')->nullable(); $table->timestamps(); }); } ``` 但是產生中文假資料得參考 [`zh_TW` 版本](https://github.com/FakerPHP/Faker/tree/main/src/Faker/Provider/zh_TW) 的規劃,當中沒有 `district` 而是把縣市跟區都放在 `city` 中,如下圖所示: ![](https://i.imgur.com/zq13f9E.png) 所以就要把 migration 中 `district` 欄位去除掉,只留下 `city` ,但經過產生假資料測試後發現偶爾會出錯,原來是跟郵遞區號(zip)有關,原因是 `zh_TW` 版本 faker 產生的 postcode 有兩種 `protected static $postcode = array('###-##', '###');` 所以 migration 中 `zip` 格式使用 `unsignedInteger` 是行不通的,後來就改成 `string` ,新的 migration 如下所示: ``` public function up() { Schema::create('user_addresses', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->string('city'); $table->string('address'); $table->string('zip'); $table->string('contact_name'); $table->string('contact_phone'); $table->dateTime('last_used_at')->nullable(); $table->timestamps(); }); } ``` *UserAddressFactory.php* ``` public function definition() { return [ 'city' => $this->faker->city, 'address' => $this->faker->streetAddress, 'zip' => $this->faker->postcode, 'contact_name' => $this->faker->name, 'contact_phone' => $this->faker->phoneNumber, ]; } ``` 在 `tinker` 中使用 `UserAddress::factory()->count(3)->create(['user_id' => 1]);` 即可製造 3 筆 user_id = 1 的 UserAddress 資料,**但前提是 Models 需要先有關聯!** ``` >>> UserAddress::factory()->count(3)->create(['user_id' => 1]); [!] Aliasing 'UserAddress' to 'App\Models\UserAddress' for this Tinker session. => Illuminate\Database\Eloquent\Collection {#3306 all: [ App\Models\UserAddress {#3310 city: "新竹縣芎林鄉", address: "南勢坑路二段402號13樓", zip: "642", contact_name: "長孫承哲", contact_phone: "(047)378-426", user_id: 1, updated_at: "2020-11-04 15:37:45", created_at: "2020-11-04 15:37:45", id: 2, }, App\Models\UserAddress {#3311 city: "高雄市桃源區", address: "勝利七街二段200號", zip: "873", contact_name: "尉遲郁", contact_phone: "(02)3791-7951", user_id: 1, updated_at: "2020-11-04 15:37:45", created_at: "2020-11-04 15:37:45", id: 3, }, App\Models\UserAddress {#3312 city: "嘉義市東區", address: "鎮新五路八段240巷910弄343號22樓", zip: "114-46", contact_name: "金馨庭", contact_phone: "+886-986-057-004", user_id: 1, updated_at: "2020-11-04 15:37:45", created_at: "2020-11-04 15:37:45", id: 4, }, ], } ``` ![](https://i.imgur.com/mI5ZHMS.png) ###### tags: `Laravel`