BuildBot

Laravel in a Container

Routes & controllers

Lesson 2 of 4

What you'll learn

  • Define routes that map URLs to controller actions
  • Capture route parameters like {id}
  • See the request lifecycle: route → controller → response

In Laravel, a route maps an HTTP method + URL to an action — usually a controller method. Routes live in routes/web.php (or routes/api.php):

use App\Http\Controllers\PostController;

Route::get('/posts',        [PostController::class, 'index']);
Route::get('/posts/{id}',   [PostController::class, 'show']);
Route::post('/posts',       [PostController::class, 'store']);

The {id} is a route parameter — Laravel pulls it out of the URL and passes it to the method:

class PostController extends Controller
{
    public function show(string $id)
    {
        $post = Post::findOrFail($id); // 404 if missing
        return view('posts.show', ['post' => $post]);
    }
}

The lifecycle is always the same: a request comes in → the router finds the matching route → it calls the controller method with the resolved parameters → the method returns a response (a view, JSON, a redirect).

Keep controllers thin

A controller's job is to coordinate: validate input, call a model or service, return a response. Business logic belongs in models/services, not stuffed into the controller — it keeps actions readable and testable.

The challenge is a tiny router that matches a method + path against route patterns and extracts params — exactly what Laravel does before calling your controller. Run it.

Match a route, capture params

Run it. The {id} pattern matches any value and captures it. Try POST /posts.

Loading editor…

Next: giving those controllers real data with migrations and Eloquent.

Sign in to save your progress across devices.