Laravel通过CMD创建模型、数据库表及带基础功能控制器的命令清单
Hey there! Let's break down all the handy Artisan commands you need for creating models, database tables (via migrations), and controllers in Laravel. I'll cover both basic standalone commands and time-saving bundled commands that set up related components together:
基础独立命令
These commands create individual components one at a time:
创建模型
基础模型创建:
php artisan make:model PostGenerates a plain model file in
app/Models/Post.php(Laravel 8+ uses theModelsnamespace by default). No migration or controller is included here.带软删除的模型:
php artisan make:model Post --soft-deletesAdds the
SoftDeletestrait to the model and automatically includes adeleted_attimestamp field in the migration (if you generate one alongside it).
创建数据库表(迁移文件)
Migrations let you define and version-control your database schema. First create the migration file, then run it to create the actual table:
创建基础迁移(指定表名):
php artisan make:migration create_posts_table --create=postsGenerates a migration file in
database/migrations/with a blueprint for creating thepoststable. The--create=postsflag tells Laravel this migration is for creating a new table.创建修改表的迁移(比如添加字段):
php artisan make:migration add_slug_to_posts_table --table=postsUse this when you need to modify an existing table (e.g., add a new column).
运行迁移生成表:
After creating your migration file and defining the table columns, run this command to apply changes to your database:php artisan migrate
创建控制器
基础空控制器:
php artisan make:controller PostControllerGenerates an empty controller in
app/Http/Controllers/PostController.php.资源控制器(带完整CRUD方法):
php artisan make:controller PostController --resourceCreates a controller with pre-defined methods for all CRUD operations:
index(),create(),store(),show(),edit(),update(),destroy(). Perfect for standard resource-based routes.
一键创建关联组件(高效开发)
These commands bundle multiple components together to speed up your workflow:
模型 + 迁移文件
php artisan make:model Post -m # 或者用完整选项名 php artisan make:model Post --migration
Generates both the model and its corresponding migration file in one go.
模型 + 迁移 + 控制器
php artisan make:model Post -mc # 等价于 php artisan make:model Post --migration --controller
Creates the model, migration, and a basic empty controller.
模型 + 迁移 + 资源控制器
php artisan make:model Post -mr # 等价于 php artisan make:model Post --migration --resource
Generates the model, migration, and a resource controller with all CRUD methods. This is great for quickly setting up a full CRUD workflow for a resource.
全能创建(模型+迁移+资源控制器+工厂+种子文件)
php artisan make:model Post -a # 等价于 php artisan make:model Post --all
This is the ultimate time-saver: it creates the model, migration, resource controller, model factory (for testing/seeding), and a seeder file all at once. Ideal for kickstarting a new feature with all necessary components.
内容的提问来源于stack exchange,提问作者mahesh

