更新Laravel 项目:使用 TDD 构建论坛 Chapter 1-2025
基于https://learnku.com/articles/10080/laravel-project-build-forum-chapter-1-using-tdd修改
模型工厂修改
factory()辅助函数已经被移除,改为使用工厂类和HashFactory Trait。
旧代码:
factory(App\User::class)->create(); // 已失效
新代码:
#一、生成初始文件与数据库
php artisan make:model Thread(User、Reply) -mcr
自动生成app\Models\Reply.php、app\Models\User.php、app\Models\Thread.php、与/migrations/2025_06_30_061057_create_replies(user、thread)_table.php
修改/migrations/2025_06_30_061057_create_replies(user、thread)_table.php中的字段类型
php artisan migrate #建立 forum 数据库,并运行迁移
#二、模型工厂
1.创建独立的工厂(相比于老版本的11.x的更新)
php artisan make:factory UserFactory --model=User
php artisan make:factory ThreadFactory --model=Thread
php artisan make:factory ReplyFactory --model=Reply
// database/factories/UserFactory.php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
protected $model = User::class;
public function definition()
{
return [
'name' => $this->faker->name(),
'email' => $this->faker->unique()->safeEmail(),
'password' => bcrypt('123456'), // 直接加密密码
'remember_token' => Str::random(10),
];
}
}
// database/factories/ThreadFactory.php
namespace Database\Factories;
use App\Models\Thread;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class ThreadFactory extends Factory
{
protected $model = Thread::class;
public function definition()
{
return [
'user_id' => User::factory(), // 自动关联 User 工厂
'title' => $this->faker->sentence(),
'body' => $this->faker->paragraph(),
];
}
}
// database/factories/ReplyFactory.php
namespace Database\Factories;
use App\Models\Reply;
use App\Models\Thread;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class ReplyFactory extends Factory
{
protected $model = Reply::class;
public function definition()
{
return [
'thread_id' => Thread::factory(), // 自动关联 Thread 工厂
'user_id' => User::factory(), // 自动关联 User 工厂
'body' => $this->faker->paragraph(),
];
}
}
#三、进入thinker生成数据
//进入thinker
php artisan thinker
// 创建 1 个用户
User::factory()->create();
// 创建 1 个帖子(自动关联用户)
\App\Models\Thread::factory()->create();
// 创建 1 条回复(自动关联用户和帖子)
\App\Models\Reply::factory()->create();
// 批量创建
User::factory()->count(10)->create();
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: