How to Use Artisan Make Controller in Laravel
Use the
php artisan make:controller ControllerName command in your Laravel project root to create a new controller file. This command generates a controller class in the app/Http/Controllers directory ready for you to add your logic.Syntax
The basic syntax for creating a controller with artisan is:
php artisan make:controller ControllerName- creates a simple controller.ControllerNameis the name you want for your controller class.- You can add options like
--resourceto create a controller with predefined methods for CRUD operations.
bash
php artisan make:controller ControllerName php artisan make:controller ControllerName --resource
Example
This example shows how to create a resource controller named ProductController. It will generate a controller with methods like index, create, store, and more.
bash
php artisan make:controller ProductController --resource
Output
Controller created successfully.
Common Pitfalls
Common mistakes when using make:controller include:
- Forgetting to run the command in the Laravel project root folder.
- Not using the
--resourceflag when you want CRUD methods generated automatically. - Using invalid controller names that don't follow PHP class naming rules.
Always check the app/Http/Controllers folder after running the command to confirm the controller was created.
bash
Wrong: php artisan make:controller productcontroller Right: php artisan make:controller ProductController
Quick Reference
| Command | Description |
|---|---|
| php artisan make:controller ControllerName | Create a basic controller |
| php artisan make:controller ControllerName --resource | Create a controller with CRUD methods |
| php artisan make:controller ControllerName --invokable | Create a controller with a single __invoke method |
| php artisan make:controller Api/ControllerName | Create controller in a subfolder (e.g., Api) |
Key Takeaways
Run
php artisan make:controller ControllerName in your Laravel project root to create a controller.Use the
--resource option to generate common CRUD methods automatically.Controller files are saved in
app/Http/Controllers by default.Ensure controller names follow PHP class naming conventions (PascalCase).
You can organize controllers in subfolders by specifying a path like
Api/ControllerName.