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 BookControllerThat 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.