MasterPHP.in
Try Compiler →
Laravel Tutorial

Creating Your First Controller in Laravel


By now your routes/web.php file has a few routes, and each one has a closure with the code inside it. For a lesson example that is fine. But imagine your invoicing app after a month of real work. One route calculates GST, another builds the list of invoices for a client, and another prepares a Razorpay payment link.

Soon web.php is 600 lines long. Routes, calculations and output all sit in one file, and finding the code for a single page means scrolling for minutes. If two developers edit the file at the same time, merge conflicts follow.

Controllers solve this. The route stays a short decision: “this URL goes there”. The actual work lives in a controller class, in its own file, with a proper name. In this lesson you will create your first controller, connect a route to it and pass route parameters into its methods.

 

Why Closures Stop Working in Real Projects

Here is a route that shows an invoice with GST, written the way you have been writing routes so far:

// routes/web.php
Route::get('/invoices/{invoice}', function (int $invoice) {
    $invoices = [
        1001 => ['client' => 'Sharma Traders', 'amount' => 12500],
        1002 => ['client' => 'Patel Stationers', 'amount' => 8400],
    ];

    $data = $invoices[$invoice] ?? abort(404);
    $gst = $data['amount'] * 0.18;

    return [
        'invoice' => $invoice,
        'client'  => $data['client'],
        'amount'  => $data['amount'],
        'gst'     => $gst,
        'total'   => $data['amount'] + $gst,
    ];
})->whereNumber('invoice')->name('invoices.show');

This works, but the problems are easy to see:

  • The route file now mixes URLs with business logic
  • The same invoice data would have to be copied into the next route that needs it
  • Ten routes like this make the file unreadable
  • Closures with a lot of logic are hard to reuse and hard to test

 

What Is a Controller?

A controller is a normal PHP class whose public methods handle incoming requests. Each method is one action, such as “show the list of invoices” or “show one invoice”. The route decides which method runs, and the method decides what to send back.

In the MVC lesson you saw that the controller sits between the request and your data. This is where that idea becomes real code. Here is the path of a request once a controller is involved:

Browser  -->  GET /invoices/1001
                  |
          routes/web.php
          (finds the matching route)
                  |
          InvoiceController::show(1001)
          (does the work)
                  |
          returns an array, a view or a response
                  |
Browser  <--  response

This is the same journey you studied in the Request Lifecycle lesson. The only new part is that the route now hands the work to a class instead of a closure.

 

Creating a Controller with Artisan

You could create a controller file by hand, but Laravel gives you a command that does it correctly. Artisan is Laravel’s command line tool, and you will study it properly in the Artisan lesson. For now, you only need one command. Open your terminal in the project folder and run:

php artisan make:controller InvoiceController

Laravel prints a success message like this:

INFO  Controller [app/Http/Controllers/InvoiceController.php] created successfully.

 

What Laravel Generated

Open app/Http/Controllers/InvoiceController.php. You will see a small class with nothing inside it yet:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    //
}

The Namespace and Location

Every controller lives in app/Http/Controllers, and its namespace is App\Http\Controllers. That namespace matches the folder path, which is how PHP’s autoloader finds the file. You already saw this folder in the Folder Structure lessons.

 

The Base Controller Class

Your class extends Controller, which is a file you can find at app/Http/Controllers/Controller.php. In a fresh Laravel project this base class is empty. It exists so that you have one place to add methods that every controller should share, if you ever need that. Extending it is the normal habit, so keep it.

 

Naming Convention

Controller names are written in PascalCase, are usually singular for the thing they manage, and end with the word Controller. So InvoiceController, ClientController and PaymentController are good names, while Invoices or invoice_controller are not. The file name must match the class name exactly, including capital letters, or the class will not load on a Linux server.

 

Writing Your First Controller Method

Now move the logic out of the closure. Replace the empty class body with two methods:

<?php

namespace App\Http\Controllers;

class InvoiceController extends Controller
{
    public function index()
    {
        return $this->invoices();
    }

    public function show(int $invoice)
    {
        $data = $this->invoices()[$invoice] ?? abort(404);
        $gst = $data['amount'] * 0.18;

        return [
            'invoice' => $invoice,
            'client'  => $data['client'],
            'amount'  => $data['amount'],
            'gst'     => $gst,
            'total'   => $data['amount'] + $gst,
        ];
    }

    private function invoices(): array
    {
        return [
            1001 => ['client' => 'Sharma Traders', 'amount' => 12500],
            1002 => ['client' => 'Patel Stationers', 'amount' => 8400],
            1003 => ['client' => 'Iyer Electricals', 'amount' => 21000],
        ];
    }
}

We removed the use Illuminate\Http\Request; line because we do not need it yet. You will learn to work with the request object in the next chapter.

There are three things to notice here:

  • index() and show() are public, so a route can call them
  • invoices() is private, so it is only a helper for this class and can never be reached from a URL
  • The hardcoded array is temporary. In the Database and Eloquent chapters it will be replaced by real data from MySQL or SQLite

The abort(404) call stops the request and shows a “Not Found” page. You will learn how Laravel handles errors in the Error Handling chapter.

 

Connecting a Route to a Controller

A controller method does nothing until a route points to it. In routes/web.php, import the controller class and give the route an array with the class and the method name:

use App\Http\Controllers\InvoiceController;

Route::get('/invoices', [InvoiceController::class, 'index'])
    ->name('invoices.index');

Route::get('/invoices/{invoice}', [InvoiceController::class, 'show'])
    ->whereNumber('invoice')
    ->name('invoices.show');

Compare this with the closure version. The routes are now two short, readable lines each, and all the logic sits in a class with a clear name. The ->name() and ->whereNumber() methods work exactly as you learned in the Named Routes and Route Parameters lessons, because only the handler changed.

InvoiceController::class gives Laravel the full class name as text, so you never type the long namespace by hand. The second item, 'show', is the method that should run.

Start the server with php artisan serve and visit these two URLs:

http://localhost:8000/invoices
http://localhost:8000/invoices/1001

You will see JSON output. When a controller method returns an array, Laravel converts it to JSON for you. Returning views and other response types is covered in the Responses lesson in the next chapter.

 

Route Parameters in Controller Methods

Look again at the show() method. The route has a {invoice} placeholder, and the method has an $invoice argument. Laravel reads the value from the URL and passes it into the method:

URL:    /invoices/1001
Route:  /invoices/{invoice}
Method: show(int $invoice)   ->   $invoice is 1001

Because you typed int, Laravel gives you a real integer. Without a type, you would get the text "1001". When a route has several placeholders, the method receives them in the same order as they appear in the URL:

Route::get('/clients/{client}/invoices/{invoice}', [InvoiceController::class, 'showForClient']);

public function showForClient(int $client, int $invoice)
{
    // $client is 7 and $invoice is 1001 for /clients/7/invoices/1001
}

Keep the argument names the same as the placeholder names. It is easier to read, and some Laravel features rely on matching names.

 

Checking Your Routes

To confirm that your routes point to the right place, run:

php artisan route:list

You will see each URL, its name and the controller method behind it, for example App\Http\Controllers\InvoiceController@show. The Resource Routes & route:list lesson explains this command in detail.

 

Organizing Controllers in Subfolders

As the app grows, you may want to group controllers, for example everything used by the admin area. Give make:controller a path and Laravel creates the folder and the right namespace:

php artisan make:controller Admin/InvoiceController

This creates app/Http/Controllers/Admin/InvoiceController.php with the namespace App\Http\Controllers\Admin. In routes/web.php, import it using that full namespace. If you also have a public InvoiceController, give one of them an alias so the names do not clash:

use App\Http\Controllers\InvoiceController;
use App\Http\Controllers\Admin\InvoiceController as AdminInvoiceController;

You will see better ways to organize larger projects in the lesson on keeping controllers thin.

 

Other Kinds of Controllers

The plain controller you built today is the base for everything else. Artisan can also generate controllers that come ready-made for specific jobs:

php artisan make:controller InvoiceController --resource
php artisan make:controller ProvisionServer --invokable

The first one creates all the CRUD methods in one go. The second creates a controller with only one action. These are the subjects of the next two lessons, so do not worry about them yet.

 

What Belongs in a Controller

A controller should coordinate, not do everything. Its job is to receive the request, ask other parts of the app to do the work and return a response. Calculations, database queries and validation rules will move into their own places as you learn the tools for them, such as Eloquent models, Form Requests and service classes.

For today, keep one rule in mind: if a controller method is growing past 15 or 20 lines, something probably belongs somewhere else. Controllers can also have middleware attached to them. That belongs to the Middleware lessons, so you will see it later.

 

Common Mistakes

Mistake 1: Forgetting to Import the Controller

Route::get('/invoices', [InvoiceController::class, 'index']);

If the use App\Http\Controllers\InvoiceController; line is missing at the top of web.php, PHP cannot work out which class you mean, and Laravel throws:

Illuminate\Contracts\Container\BindingResolutionException: Target class [InvoiceController] does not exist.

Add the use statement. Also check that the class name and file name match exactly.

 

Mistake 2: Pointing to a Method That Does Not Exist

Route::get('/invoices/{invoice}', [InvoiceController::class, 'display']);

If the controller has show() but no display(), you get:

BadMethodCallException: Method App\Http\Controllers\InvoiceController::display does not exist.

Check the spelling in the route against the method name in the class.

 

Mistake 3: Method Needs a Value the Route Does Not Provide

Route::get('/invoices', [InvoiceController::class, 'show']);

The show() method asks for an $invoice, but this URL has no {invoice} placeholder. Laravel does not know where to get the value:

Illuminate\Contracts\Container\BindingResolutionException: Unable to resolve dependency [Parameter #0 [ <required> int $invoice ]] in class App\Http\Controllers\InvoiceController

Make the route and the method agree. Either add the placeholder to the route, or remove the argument from the method.

 

Mistake 4: Forgetting to Return Something

public function index()
{
    $this->invoices();
}

There is no return, so there is no error either. The browser just shows a blank page. If a page is empty and no error appears, check that your method returns something.

 

Mistake 5: Using the Old String Syntax

Older tutorials write controller routes as text, like 'InvoiceController@index'. That style was designed for older Laravel versions and does not match how modern Laravel resolves controllers, so it often fails with a “class does not exist” error. Always use the array form with InvoiceController::class.

 

Mistake 6: Putting Everything in One Method

It is tempting to paste the whole closure into one big controller method and call it done. That moves the mess to a new file instead of removing it. Keep each method focused on one action, and move shared logic into private helpers or, later, into their own classes.

 

Quick Summary

  • A controller is a PHP class in app/Http/Controllers whose public methods handle requests.
  • Create one with php artisan make:controller InvoiceController.
  • Name controllers in PascalCase and end the name with Controller.
  • Connect a route with [InvoiceController::class, 'show'] and import the class with use.
  • Route parameters are passed to the method as arguments, in the same order as in the URL.
  • Names, constraints and the other route features you learned earlier work the same way with controllers.
  • Only public methods can be reached by routes. Private methods are helpers.
  • Use make:controller Admin/InvoiceController to create controllers in subfolders.
  • Run php artisan route:list to confirm where each route points.
  • Keep controllers short and focused. The route chooses the action, and the controller coordinates it.

 

What’s Next

You have one controller with two actions, written by hand. But most apps need the same set of actions again and again: list, show, create, edit and delete. In the next lesson, Resource Controllers (Full CRUD Structure), you will let Laravel generate all seven methods at once and connect them with a single route line.

Frequently Asked Questions

No. Simple routes can still use closures, and Laravel will run them without any problem. But for any route with real logic, or any page that will grow, a controller is the better choice. A good rule is to use closures for quick tests and controllers for everything you plan to keep.
Yes. A controller is just a PHP class, so you can create the file by hand inside app/Http/Controllers and set the correct namespace. Artisan is only a shortcut that avoids typing mistakes. Most developers use the command because it takes a few seconds and always gets the namespace right.
It is a naming convention that makes your project easy to read. When you see InvoiceController in a route or an error message, you know immediately that it is a controller and not a model or a service. Laravel does not force this, but following it is part of writing code the Laravel community expects.
A method can return text, an array, a JSON response, a view or a redirect. Laravel converts arrays and objects to JSON automatically, and turns views into HTML. Each of these has its own lesson in the Requests, Responses and Middleware chapter.
Yes. Run php artisan make:controller Admin/InvoiceController and Laravel creates the folder and sets the right namespace for you. In your route file, import the class using the full namespace. Subfolders are a good way to separate areas like admin, public site and API as the project grows.

Share this tutorial