Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 67 ยท Routing and Controllers

Controllers

Learn Laravel controllers: make:controller, single-action and resource controllers, constructor and method injection, and controller middleware, plus a runnable dispatcher.

Closures are fine for a three-line route, but they do not scale. A real page needs to load data, check rules, call services and choose a response. Putting all of that in routes/web.php makes the file long, hard to test, and impossible to cache well. A controller is simply a class whose methods handle requests, so related logic lives together and the route file stays a readable map of your application.

In this lesson you will generate controllers with artisan, use resource and single-action controllers, see how Laravel injects dependencies into constructors and methods, and attach middleware. You will also build a small dispatcher that uses PHP reflection to do the same autowiring, so the "magic" becomes ordinary code. If reflection is new to you, see PHP reflection.

Laravel code is shown read-only. The runnable examples are plain-PHP stand-ins; each one says which part of real Laravel it imitates.

Creating a controller

Controllers live in app/Http/Controllers. Generate one with artisan:

Terminal
php artisan make:controller PostController

The class is plain PHP, usually extending nothing in a Laravel 13 project (the skeleton still has an empty base Controller class you may extend):

PHP
namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index()
    {
        return view('posts.index', ['posts' => Post::latest()->get()]);
    }

    public function show(Post $post)
    {
        return view('posts.show', ['post' => $post]);
    }
}

Point routes at it with an array of class and method name:

PHP
Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
Route::get('/posts/{post}', [PostController::class, 'show'])->name('posts.show');

Using PostController::class instead of a string gives your editor something to navigate and refactor. Combine it with a controller group to name the class once.

Single-action controllers

When a controller does exactly one thing, give it an __invoke method and route to the class directly:

Terminal
php artisan make:controller ShowDashboard --invokable
PHP
class ShowDashboard extends Controller
{
    public function __invoke()
    {
        return view('dashboard');
    }
}

Route::get('/dashboard', ShowDashboard::class);

Single-action controllers are a good home for pages that do not fit the standard create-read-update-delete shape, such as "export report" or "webhook receiver".

Resource controllers

Most data-driven pages need the same seven operations. A resource controller names them and a single line registers all the routes:

Terminal
php artisan make:controller PostController --resource --model=Post
PHP
Route::resource('posts', PostController::class);
Verb URI Action Route name
GET /posts index posts.index
GET /posts/create create posts.create
POST /posts store posts.store
GET /posts/{post} show posts.show
GET /posts/{post}/edit edit posts.edit
PUT/PATCH /posts/{post} update posts.update
DELETE /posts/{post} destroy posts.destroy

create and edit show forms; store and update receive them. For JSON APIs, which need no forms, use Route::apiResource('posts', PostController::class) to skip create and edit. Trim either with ->only(['index', 'show']) or ->except(['destroy']). The --model option makes artisan type-hint the model in the generated methods, so implicit binding applies. Nested resources use dot notation: Route::resource('posts.comments', CommentController::class).

Dependency injection

Laravel builds your controller through the service container, which reads type hints and supplies matching objects. Two places benefit.

Constructor injection is for dependencies the whole controller needs:

PHP
use App\Services\PostPublisher;

class PostController extends Controller
{
    public function __construct(private PostPublisher $publisher) {}
}

Method injection is for things only one action needs, and it mixes freely with route parameters:

PHP
public function store(Request $request, PostPublisher $publisher)
{
    $publisher->publish($request->string('title'));
    return to_route('posts.index');
}

public function update(Request $request, Post $post)
{
    // $request and $post are both injected; $post comes from the URL
}

Type-hinted classes come from the container; plain route parameters () are filled in by name or position. That is the entire mechanism, and you will build it yourself below. For the pattern behind it, see dependency injection in PHP.

flowchart LR
    A["Route matches<br/>posts.store"] --> B["Container builds<br/>PostController"]
    B --> C["Constructor<br/>dependencies injected"]
    C --> D["Method arguments<br/>resolved: Request, services, models"]
    D --> E["store() runs"]
    E --> F["Return value becomes a response"]

The container builds the controller first, then resolves each argument of the action method.

Controller middleware

Middleware can be attached in the route file, as in Route::resource(...)->middleware('auth'). To keep it with the controller, implement the HasMiddleware interface:

PHP
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class PostController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            'auth',
            new Middleware('log-access', only: ['index']),
            new Middleware('subscribed', except: ['index', 'show']),
        ];
    }
}

Plain names apply to every action; a Middleware object can restrict by action with only or except. Older tutorials call $this->middleware() in the constructor, which modern Laravel no longer supports on the base class. Middleware explains what such classes do.

What belongs in a controller

A controller's job is to translate HTTP into application calls and back: read input, call a service, pick a response. Validation, business rules and database details should live elsewhere. The usual symptom of a "fat controller" is a method that grows past a screenful; architecture patterns shows how to refactor it.

Autowiring with reflection

This stand-in has a container that builds a controller by reading constructor type hints, then calls an action while resolving class-typed arguments from the container and scalar arguments from route parameters (cast to the declared type). Real Laravel does the same with much more care: caching, contextual rules, enum and model binding.

PHP A mini controller dispatcher with autowiring

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that nobody called new PostController(new PostRepository()). The constructor's type hint was enough. Adding another dependency to a controller means adding one parameter, nothing else.

Expanding a resource

Route::resource is a table generator. The stand-in below produces the seven rows for a name, then applies only and except filters, which is all the real method does conceptually (plus handling nested names, parameters and shallow routes).

PHP What Route::resource generates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which artisan option creates a controller with the seven resource methods?

    make:controller PostController --resource generates index, create, store, show, edit, update and destroy. Use --api to skip create and edit.
  2. 2. How do you route to a single-action controller named ShowDashboard?

    A class with an __invoke method can be given directly as the action.
  3. 3. What is the difference between constructor injection and method injection in a controller?

    Both use the container. Put shared dependencies in the constructor and one-off ones (like Request or a service used by a single action) in the method signature.
  4. 4. How does a modern Laravel controller declare its own middleware?

    The HasMiddleware interface requires a static middleware() method. Entries can be plain names or Middleware objects with only/except.

Summary

  • Controllers are plain classes that group request-handling methods; generate them with php artisan make:controller.
  • Use --invokable for single-action controllers and --resource (or apiResource) for the standard seven operations.
  • The container builds controllers and resolves type-hinted arguments in constructors and action methods; route parameters fill the rest.
  • Implement HasMiddleware to attach middleware with only and except rules.
  • Keep controllers thin: read input, call a service, return a response.

Next: Requests and Responses