Controllers — Laravel

A controller is a class in app/Http/Controllers that gathers the request-answering code of one feature. Each of its methods (functions inside the class)…

In the Routing lesson, each route carried its own function in routes/web.php. With five addresses the file still reads fine. But once the Library app has dozens of addresses, the file becomes like one plain PHP file holding every page at once.

A controller moves the code inside those route functions out of routes/web.php. A controller is a class that gathers the code answering requests for one feature, for example the books feature. The route only has to point to the controller: "this address is answered by that method". Method here means a class method (a function inside a class), not an HTTP method like GET.

Picture the book desk at the library. The clerk at the door only directs visitors, and all book matters are handled at one desk. At that desk, each matter has its own clerk: one shows the list of books, another finds a single book. The clerk at the door is Laravel with its list of routes, the desk is the controller, and each clerk at the desk is one method.

Creating a controller

A controller is made with Artisan:

php artisan make:controller BookController

The terminal answers:

   INFO  Controller [/home/budi/library/app/Http/Controllers/BookController.php] created successfully.

The new file holds a class that is still empty:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class BookController extends Controller
{
    //
}

Filling in the methods

Fill in two methods for the Library app. The data is still a plain array. In the Eloquent lesson, this array is replaced by data from the database.

class BookController extends Controller
{
    private array $books = [
        1 => ['id' => 1, 'title' => 'The Rainbow Troops', 'author' => 'Andrea Hirata'],
        2 => ['id' => 2, 'title' => 'This Earth of Mankind', 'author' => 'Pramoedya Ananta Toer'],
        3 => ['id' => 3, 'title' => 'Beauty Is a Wound', 'author' => 'Eka Kurniawan'],
    ];

    public function index()
    {
        return response()->json(array_values($this->books));
    }

    public function show(string $id)
    {
        if (! isset($this->books[$id])) {
            return response()->json(['message' => 'Book not found'], 404);
        }

        return response()->json($this->books[$id]);
    }
}

Connecting a route to the controller

Now each route in routes/web.php only has to point to one controller method:

<?php

use App\Http\Controllers\BookController;
use Illuminate\Support\Facades\Route;

Route::get('/books', [BookController::class, 'index'])->name('books.index');
Route::get('/books/{id}', [BookController::class, 'show'])->name('books.show');

When the route matches, Laravel creates a BookController object, then calls its method:

Request Route Laravel calls Answer
GET /books books.index index() 200 the list of three books
GET /books/2 books.show show('2') 200 {"id":2,"title":"This Earth of Mankind",...}
GET /books/9 books.show show('9') 404 {"message":"Book not found"}

Resource controllers: seven methods at once

A feature like books nearly always needs the same seven actions. Artisan can create all seven methods right away. They are still empty, holding only the comment //:

php artisan make:controller BookController --resource

--resource can be shortened to -r. Then one route line registers them all:

Route::resource('books', BookController::class);

These are the routes that line registers, seen with php artisan route:list:

$ php artisan route:list --except-vendor

  GET|HEAD        books ................... books.index › BookController@index
  POST            books ................... books.store › BookController@store
  GET|HEAD        books/create .......... books.create › BookController@create
  GET|HEAD        books/{book} .............. books.show › BookController@show
  PUT|PATCH       books/{book} .......... books.update › BookController@update
  DELETE          books/{book} ........ books.destroy › BookController@destroy
  GET|HEAD        books/{book}/edit ......... books.edit › BookController@edit

                                                            Showing [7] routes

Seven routes from one line. BookController@index means the method index in BookController. The seven methods: index (the list), create (the add form), store (save the new one), show (one book), edit (the edit form), update (save the changes), destroy (delete). The parameter is named {book}, the singular of books. /books/create is registered before /books/{book}, so the ordering trap from the Routing lesson (a parameter that captures the word create) doesn't happen.

For an API (an app that answers with JSON data) with no form pages, use php artisan make:controller BookController --api and Route::apiResource(...). The result is five routes, without create and edit.

⚠️ Why doesn't the controller answer?

TL;DR: A controller is a class in app/Http/Controllers that gathers the request-answering code of one feature. Each of its methods (functions inside the class) answers one route. Create it with php artisan make:controller BookController, fill in its methods, then connect it with Route::get('/books', [BookController::class, 'index']) plus use App\Http\Controllers\BookController;. The address parameter {id} arrives as a method argument. Adding --resource (or -r) to that command creates seven methods: index, create, store, show, edit, update, destroy. Route::resource('books', BookController::class) registers their seven routes. For an API with no form pages, --api and Route::apiResource make five, without create and edit.

⚡ Create a controller

Write:

php artisan make:controller BookController

Meaning: A controller is a class in app/Http/Controllers that gathers the request-answering code of one feature. This command creates the file app/Http/Controllers/BookController.php holding an empty class. A controller's name ends in Controller and is written in PascalCase (each word starts with a capital letter).

⚡ The route only points

Write:

use App\Http\Controllers\BookController;

Route::get('/books/{id}', [BookController::class, 'show']);

Meaning: [BookController::class, 'show'] means "the class BookController, the method show". Method here means a function inside the class, not an HTTP method. When the address matches, Laravel calls that method, and the {id} value from the address arrives as its argument: show(string $id). The use line makes the name BookController point to the right class. Without that line, the request fails with Target class [BookController] does not exist.

In the exercise, the method index() (the one that answers the list) must return a product list that holds a product named Laptop, and the answer is built with response()->json(...).

⚡ Seven routes from one line

Guess first: Route::resource('books', BookController::class) registers routes for all the usual book actions: the list, the add form, save, one book, the edit form, save the changes, and delete. How many routes?

Seven: index, create, store, show, edit, update, destroy. Route::apiResource makes only five, without create and edit (the two form pages), for an API that answers with JSON.

Meaning: php artisan make:controller BookController --resource (or -r) creates all seven methods in the controller at once, still empty.

What you will learn