iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 28
1
Software Development

從零開始的Laravel RESTful api系列 第 28

Day 28 : database seeding

對於 category 來說,一般而言都是由系統手動去增減,否則過多的 category 會造成不必要的麻煩 ( 個人私自認為 hashtag 就是一個例子,有非常多的 hashtag 其實用處不大 ),不過在這次主題中,我會隨機仿造幾個 category,而 database seeding 可以幫我們完成這件事,不過此次鐵人賽的主題不在測試這一塊,因此不會太過深入探討此部份。

Factory

User

在新增 Laravel 專案後,已經預設存在 UserFactory,檔案位置以及程式碼如下:

*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,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
});

當然此處我們會依據自己定義的 user table 做修改

修改後的情形如下:

*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,
        'email' => $faker->unique()->safeEmail,
        // 'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        // 'remember_token' => Str::random(10),
        'is_admin' => false,
        'api_token' => Str::random(60),
    ];
});

Category

  • 建立 factory

    factory 定義資料該如何偽造

    $ php artisan make:factory CategoryFactory
    

    檔案位置與程式碼如下:

    *database/factories/CategoryFactory.php

    <?php
    
    /** @var \Illuminate\Database\Eloquent\Factory $factory */
    
    use App\Model;
    use Faker\Generator as Faker;
    
    $factory->define(Model::class, function (Faker $faker) {
        return [
            //
        ];
    });
    

    或者也可以定義所屬的 Model

    $ php artisan make:factory CategoryFactory --model=Category
    

    檔案位置與程式碼如下:

    *database/factories/CategoryFactory.php

    <?php
    
    /** @var \Illuminate\Database\Eloquent\Factory $factory */
    
    use App\Category;
    use Faker\Generator as Faker;
    
    $factory->define(Category::class, function (Faker $faker) {
        return [
            //
        ];
    });
    
  • 定義 factory

    Category 只要偽造 name 就行了,至於偽造是來自於 Faker 這個 class,若要看詳細的文件可以參考 github

    'name' => $faker->name
    

    或者是隨機生成一個字串也行

    // 記得 use Illuminate\Support\Str;
    'name' => Str::random(10)
    

    完整程式碼:
    *CategoryFactory.php

    <?php
    
    /** @var \Illuminate\Database\Eloquent\Factory $factory */
    
    use App\Category;
    use Faker\Generator as Faker;
    
    $factory->define(Category::class, function (Faker $faker) {
        return [
            'name' => $faker->name
        ];
    });
    

Seeder

User

  • 建立 seeder
$ php artisan make:seeder UsersTableSeeder

而其檔案位置以及程式碼如下:

*database/seeds/UsersTableSeeder.php

<?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //
    }
}
  • 定義 seeder

此處會根據剛剛的 factory 生成假資料,除此之外,假資料的數量可以在此設定

<?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\User::class, 10)->create();
    }
}
  • 註冊 seeder

    註冊的地方如下 ( 正好可以將註解掉的部份取消 ):

    *database/seeds/DatabaseSeeder.php

    <?php
    
    use Illuminate\Database\Seeder;
    
    class DatabaseSeeder extends Seeder
    {
        /**
         * Seed the application's database.
         *
         * @return void
         */
        public function run()
        {
            $this->call(UsersTableSeeder::class);
        }
    }
    

Category

  • 建立 seeder

    $ php artisan make:seeder CategoriesTableSeeder
    
  • 定義 seeder

    *CategoriesTableSeeder.php

    <?php
    
    use Illuminate\Database\Seeder;
    
    class CategoriesTableSeeder extends Seeder
    {
        /**
         * Run the database seeds.
         *
         * @return void
         */
        public function run()
        {
            factory(App\Category::class, 10)->create();
        }
    }
    
  • 註冊 seeder

    *DatabaseSeeder.php

    <?php
    
    use Illuminate\Database\Seeder;
    
    class DatabaseSeeder extends Seeder
    {
        /**
         * Seed the application's database.
         *
         * @return void
         */
        public function run()
        {
            $this->call(UsersTableSeeder::class);
            $this->call(CategoriesTableSeeder::class);
        }
    }
    

Seeding

factory 和 seeder 設定完成後,首先先進行 autoload 的動作

$ composer dump-autoload

之後進行以下指令就可以生成自己的假資料

$ php artisan db:seed

image alt

透過 mysql 查看 database

  • users table

image alt

  • categories table

image alt

生完假資料後,接下來我們重新處理 post 的部份,也就是為其添加 categories。

參考資料:

  1. Database seeding : https://laravel.com/docs/6.x/seeding
  2. Database faker : https://github.com/fzaninotto/Faker

上一篇
Day 27 : category ( migration & Model )
下一篇
Day 29 : category ( modify PostsController )
系列文
從零開始的Laravel RESTful api30

尚未有邦友留言

立即登入留言