How to Create a Controller in Laravel

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.

1. Create a Controller Using Artisan Command

Laravel provides a simple command to generate a controller through Artisan CLI (Command Line Interface).

php artisan make:controller UserController

2. Add a Function to the Controller

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
    public function index()
    {
        return "Welcome to User Controller!";
    }
}

3. Define a Route for the Controller

use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);

Now, when you visit http://127.0.0.1:8000/users

4. Create a Resource Controller (Optional)

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);

5. API Controller

For API-based projects, use the --api flag to exclude view-related methods:

php artisan make:controller Api/UserController --api

6. Summary

CommandDescription
php artisan make:controller NameControllerCreate a basic controller
php artisan make:controller NameController --resourceCreate a resource controller with CRUD methods
php artisan make:controller Api/NameController --apiCreate a controller for APIs only
Comments