How to Use Artisan Make Model in Laravel
Use the
php artisan make:model ModelName command in your Laravel project root to create a new model file. You can add options like -m to create a migration or -c to create a controller alongside the model.Syntax
The basic syntax for creating a model with artisan is:
php artisan make:model ModelName: Creates a new model namedModelName.-mor--migration: Also creates a migration file for the model's database table.-cor--controller: Creates a controller for the model.-for--factory: Creates a factory for generating fake data.-ror--resource: Creates a resource controller with CRUD methods.
bash
php artisan make:model ModelName [-m] [-c] [-f] [-r]
Example
This example creates a model named Post with a migration and a controller:
bash
php artisan make:model Post -m -c
Output
Model created successfully.
Created Migration: 2024_06_01_000000_create_posts_table.php
Created Controller: app/Http/Controllers/PostController.php
Common Pitfalls
Common mistakes when using make:model include:
- Forgetting to run
php artisan migrateafter creating migrations. - Not using the correct model name format (should be singular and PascalCase, e.g.,
UserProfile). - Creating models without necessary options, leading to extra manual steps.
Example of wrong and right usage:
bash
php artisan make:model posts # Wrong: model name should be singular and PascalCase php artisan make:model Post -m -c # Right: creates model, migration, and controller
Quick Reference
| Option | Description |
|---|---|
| -m, --migration | Create a migration file for the model's table |
| -c, --controller | Create a controller for the model |
| -f, --factory | Create a factory for generating fake data |
| -r, --resource | Create a resource controller with CRUD methods |
| -a, --all | Create migration, factory, controller, and resource controller |
Key Takeaways
Use
php artisan make:model ModelName to quickly create a model file.Add
-m to generate a migration file alongside the model.Use singular, PascalCase names for models to follow Laravel conventions.
Combine options like
-c and -f to create controllers and factories automatically.Always run
php artisan migrate after creating migrations.