Skip to the workspace
Pebellslearn by building
Controllers  ›  Lesson

Basic Controllers

Basic controllers 12 minA controller is a class in app/Http/Controllers whose public methods handle requests, and routes point at a method with a [Class::class, 'method'] pair instead of holding the logic themselves.

laravel / Basic Controllers

Explore each scene at your own pace.

01 · The rule

The rule

Basic Controllers

Closures in routes/web.php are perfect for a page or two. By the time Lendly has book lists, detail pages, forms and loan history, the routes file is hundreds of lines of mixed logic. Controllers move the logic into classes, and the routes file goes back to being a map.

The rule

Routes point; controllers act.

Create a controller with Artisan:

php artisan make:controller BookController

That makes app/Http/Controllers/BookController.php. Each public method handles one kind of request:

namespace App\Http\Controllers;

use App\Models\Book;

class BookController extends Controller
{
    public function index()
    {
        return view('books.index', ['books' => Book::all()]);
    }

    public function show(string $id)
    {
        return view('books.show', ['book' => Book::findOrFail($id)]);
    }
}

A route now names the class and the method as a pair:

use App\Http\Controllers\BookController;

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

Everything you learned about closures still holds:

  • Route parameters arrive as method arguments, in order.
  • The return value becomes the response: a view, JSON, a redirect.
  • Names, constraints and middleware chain onto the route exactly as before.

findOrFail looks a book up by id and sends a 404 if there is none, so the view never receives a missing book.

The base Controller class that make:controller extends is empty in Laravel 11 and 12. It is a place for your own shared helpers.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.