Factory(建立測試資料)

建立 Factory 檔案

使用 Artisan 指令建立 Factory 並指定關聯的模型:

php artisan make:factory PostFactory --model=Post

定義生成資料內容

⚠️ Laravel 8 開始,faker() 被改為 fake(),依照 Laravel 版本使用正確方法。以下為 Laravel 10 寫法。

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
use App\Models\Post;

class PostFactory extends Factory
{
    /**
     * 指定對應的模型
     *
     * @var string
     */
    protected $model = Post::class;

    /**
     * 定義模型的預設資料狀態
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'title' => fake()->unique()->name(),
            'content' => fake()->sentence(),
            'note' => Str::random(10),
            'created_at' => now(),
        ];
    }
}

建立測試資料

// 建立模型資料但不儲存到資料庫(回傳為模型實例)
$post = Post::factory()->make();

// 建立並儲存模型資料到資料庫
$post = Post::factory()->create();

參考資源