How to Create Controller in Laravel: Simple Guide
To create a controller in Laravel, use the
php artisan make:controller ControllerName command in your terminal. This generates a new controller file in the app/Http/Controllers directory ready for you to add methods.Syntax
The basic syntax to create a controller in Laravel is:
php artisan make:controller ControllerNameHere:
- php artisan runs Laravel's command-line tool.
- make:controller is the command to generate a controller.
- ControllerName is the name you want to give your controller, usually ending with
Controller.
bash
php artisan make:controller ExampleController
Example
This example shows how to create a simple controller named ProductController and add a method to return a string.
php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ProductController extends Controller { public function index() { return 'Welcome to the Product page!'; } }
Output
When you route to ProductController@index, the browser will display: Welcome to the Product page!
Common Pitfalls
Common mistakes when creating controllers in Laravel include:
- Not running the
php artisan make:controllercommand inside the Laravel project directory. - Forgetting to add the controller's namespace or use statement when referencing it in routes.
- Not defining methods inside the controller before trying to use them in routes.
- Using incorrect controller names that do not follow the PascalCase convention ending with
Controller.
php
// Wrong way: // Trying to use a controller without creating it Route::get('/products', 'ProductController@index'); // Right way: // Create controller first php artisan make:controller ProductController // Then define route with full namespace or use statement use App\Http\Controllers\ProductController; Route::get('/products', [ProductController::class, 'index']);
Quick Reference
| Command | Description |
|---|---|
| php artisan make:controller ControllerName | Creates a new controller file |
| php artisan make:controller ControllerName --resource | Creates a controller with resource methods (index, create, store, etc.) |
| php artisan make:controller ControllerName --invokable | Creates a single-action controller |
| app/Http/Controllers | Default directory where controllers are stored |
Key Takeaways
Use the command 'php artisan make:controller ControllerName' to create a new controller.
Controllers are stored in the 'app/Http/Controllers' directory by default.
Always define methods inside your controller before using them in routes.
Use PascalCase and end controller names with 'Controller' for clarity.
Use resource or invokable flags for specialized controller types.