iT邦幫忙

第 11 屆 iThome 鐵人賽

3

API開完後想用些測試資料來檢查自己寫的程式有沒有問題,但又不想一筆一筆資料自己輸入的時候怎麼辦呢? Laravel的Factory可以自動幫你產生假資料,只要告訴他你想要建立的資料內容和資料筆數就可以了。

第一步:建立factory

 php artisan make:factory Factory名稱 --model=model名稱

第二步:畫出假資料的藍圖

告訴Laravel你的假資料每個欄位應該是什麼資料型態、屬性等。
database/factories/UserFactory.php:

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\User;
use Faker\Generator as Faker;
use Illuminate\Support\Str;

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
    ];
});


第三步:開始製造假資料

php artisan tinker

會看到三個小於:
https://ithelp.ithome.com.tw/upload/images/20200107/20120024E8Rb9LmHAI.png

輸入你要填充假資料對映的Model:

factory(App\User::class,5)->create() 

https://ithelp.ithome.com.tw/upload/images/20200107/20120024ui2KNxMr0U.png
這樣假資料就建立完成!


上一篇
Day 33 Laravel 實做雙人橋牌之心得分享
下一篇
Day 35 Laravel 實作 LINE Bot 小幫手筆記
系列文
後端基礎PHP+Mysql & Laravel 30日養成計畫36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言