Laravel follows the MVC (Model-View-Controller) architecture, which separates the logic of your application into three parts — Models, Views, and Controllers.
Controllers act as the middle layer between Models (database) and Views (frontend). They handle user requests, process data, and return responses.
In this tutorial, you’ll learn how to create a controller in Laravel using Artisan commands and how to use it in your routes.
Laravel provides a simple command to generate a controller through Artisan CLI (Command Line Interface).
php artisan make:controller UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
return "Welcome to User Controller!";
}
}
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);
Now, when you visit http://127.0.0.1:8000/users
If you’re building a CRUD (Create, Read, Update, Delete) system, you can use a resource controller to automatically generate all common methods.
php artisan make:controller ProductController --resource
This creates a controller with pre-defined methods like:
index() → Display all records
create() → Show form to add new record
store() → Save data
show() → Display a single record
edit() → Show edit form
update() → Update data
destroy() → Delete record
Then define a resource route:
Route::resource('products', ProductController::class);For API-based projects, use the --api flag to exclude view-related methods:
php artisan make:controller Api/UserController --api
| Command | Description |
|---|---|
php artisan make:controller NameController | Create a basic controller |
php artisan make:controller NameController --resource | Create a resource controller with CRUD methods |
php artisan make:controller Api/NameController --api | Create a controller for APIs only |