Laravel 创建一个模块简要流程

由 Jefsky 发布于 2024-01-19

创建数据迁移文件

php artisan make:migration create_links_table

修改迁移文件

{timestamp}_create_links_table.php

  • 迁移时调用 up()
  • 回滚时调用 down()

创建数据表

Schema::create('links', function (Blueprint $table) {
      $table->id();
      $table->string('title'),
      $table->timestamps();
});
注意
  • migrate 命令只执行未未迁移的文件,执行完成后将生成 2 个表:
    • migrations —— 迁移版本
    • columns —— 数据

执行迁移

php artisan migrate

创建模型

php artisan make:model Link

创建模型工厂文件

php artisan make:factory LinkFactory

修改工厂文件

public function definition()
{
    return [
        'name' => $this->faker->name()
    ];
}
  • Faker 是一个假数据生成库,name() 是 faker 提供的 API ,随机生成人名。我们用来填充 name 专栏名称字段。

创建填充文件

php artisan make:seeder LinksSeeder

  • run() 方法会在 db:seed 执行

修改填充文件

    public function run()
    {
        Link::factory()->count(10)->create();
    }
  • 生成10条数据

注册数据填充

databases/seeders/DatabaseSeeder.php

public function run()
{
    $this->call(ColumnsSeeder::class);
}
注意
  • 需要移除无用的数据填充,以防止重复填充

执行数据填充

php artisan db:seed