0
0
LaravelHow-ToBeginner · 3 min read

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 named ModelName.
  • -m or --migration: Also creates a migration file for the model's database table.
  • -c or --controller: Creates a controller for the model.
  • -f or --factory: Creates a factory for generating fake data.
  • -r or --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 migrate after 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

OptionDescription
-m, --migrationCreate a migration file for the model's table
-c, --controllerCreate a controller for the model
-f, --factoryCreate a factory for generating fake data
-r, --resourceCreate a resource controller with CRUD methods
-a, --allCreate 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.