Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 67 ยท Routing and Controllers

Routing Basics

Learn Laravel routing: routes/web.php, HTTP verbs, closures, route parameters, optional parameters, constraints, named routes and route:list, with a mini router.

A route is a promise: "when a request arrives with this HTTP method and this URL path, run this code". Every Laravel application is, at its heart, a table of such promises. The framework reads the table, finds the first entry that matches the incoming request, runs its code, and turns the return value into a response.

In this lesson you will write routes for the most common situations: plain pages, parameters in the URL, optional parameters, constraints that reject bad input, and named routes so you never hard-code a URL twice. The ideas behind them are not Laravel-specific, so you will also build a small runnable router in plain PHP. If you want the plain-PHP background first, read routing in PHP; to see where routing sits in a request, see the request lifecycle.

Laravel code in this lesson is shown in read-only blocks, because Laravel cannot run inside your browser. The runnable examples are plain-PHP stand-ins that copy the behavior, not the real framework code. Each one says what it imitates.

Where routes live

In a fresh Laravel 13 project, web routes go in routes/web.php. The file is loaded by bootstrap/app.php, which tells the framework which route files exist:

PHP
// bootstrap/app.php (shortened)
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->create();

Routes in web.php get the web middleware group: sessions, cookies, CSRF protection and a few more. There is no routes/api.php until you run php artisan install:api; API routes are covered in building JSON APIs.

A first route looks like this:

PHP
// routes/web.php
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/about', fn () => 'We build tutorials.');

The first argument is the URI, the second is the action. A closure is the simplest action; a controller method is the usual choice once the logic grows (see controllers). Whatever you return is converted into a response: a string becomes an HTML body, an array becomes JSON, a view becomes rendered HTML. Requests and responses covers the details.

HTTP verbs

The router has one method per HTTP verb:

PHP
Route::get('/posts', fn () => 'list');            // read
Route::post('/posts', fn () => 'create');         // create
Route::put('/posts/{id}', fn () => 'replace');    // replace
Route::patch('/posts/{id}', fn () => 'update');   // partial update
Route::delete('/posts/{id}', fn () => 'delete');  // remove
Route::options('/posts', fn () => 'allowed verbs');

The same URI can appear several times with different verbs; the verb is part of the match. For several verbs at once use Route::match(['get', 'post'], '/search', ...), or Route::any(...) for all of them. Two shortcuts save boilerplate: Route::view('/pricing', 'pricing') renders a view without a closure, and Route::redirect('/old', '/new', 301) sends a permanent redirect.

HTML forms can only send GET and POST. For PUT, PATCH and DELETE, a form includes a hidden _method field, which Blade writes for you with @method('DELETE'). See forms, CSRF and assets.

Route parameters

Curly braces capture part of the path and hand it to your action:

PHP
Route::get('/users/{id}', function (string $id) {
    return "User $id";
});

Route::get('/posts/{post}/comments/{comment}', function (string $post, string $comment) {
    return "Comment $comment on post $post";
});

Parameters are matched by their position in the URI, so the closure's argument names do not have to match the placeholder names. If your action also asks for services (a Request, for example), Laravel injects them through the service container; put injected types first or in any position, since only the route parameters are positional.

A parameter matches any characters except /. That is why /users/42 matches but /users/42/extra does not.

Optional parameters

Add ? after the name and give the argument a default value:

PHP
Route::get('/greet/{name?}', function (?string $name = null) {
    return 'Hello, '.($name ?? 'stranger');
});

Without the default, PHP would raise an error when the segment is missing. Only trailing parameters can be optional.

Constraints

By default accepts abc as happily as 42. Constraints narrow what a parameter may match; a request that fails the constraint falls through to a 404 as if the route did not exist:

PHP
Route::get('/users/{id}', fn (string $id) => "User $id")
    ->where('id', '[0-9]+');

Route::get('/users/{id}', fn (string $id) => "User $id")->whereNumber('id');
Route::get('/tags/{slug}', fn (string $slug) => $slug)->whereAlphaNumeric('slug');
Route::get('/orders/{uuid}', fn (string $uuid) => $uuid)->whereUuid('uuid');
Route::get('/status/{type}', fn (string $type) => $type)->whereIn('type', ['open', 'closed']);

To apply one rule to every route that uses a given parameter name, register a global pattern in AppServiceProvider::boot():

PHP
Route::pattern('id', '[0-9]+');

Constraints are the first line of defense, not the only one. They keep obviously wrong URLs away from your code, but you still validate real input.

Named routes

If you write /posts/42 in twenty places and later change it to /articles/42, you have twenty edits to make. A named route gives the URL a stable label:

PHP
Route::get('/posts/{post}', fn (string $post) => "Post $post")
    ->name('posts.show');

$url = route('posts.show', ['post' => 42]);          // /posts/42 (absolute URL)
$withQuery = route('posts.show', ['post' => 42, 'ref' => 'home']);
// extra keys become the query string: ...?ref=home

The route() helper builds the URL from the name, filling in parameters and appending leftovers as a query string. Redirects use the same names: return to_route('posts.show', ['post' => 42]);. Dot-separated names such as posts.show are a convention that pays off when you group routes (the next lesson shows how).

flowchart LR
    A["Request: GET /posts/42"] --> B["Router table"]
    B -->|"verb and path match"| C["posts.show"]
    C --> D["Action runs with id = 42"]
    B -->|"path matches, verb differs"| E["405 Method Not Allowed"]
    B -->|"nothing matches"| F["404 Not Found"]

The router checks the verb and path together; the outcome is a match, a 405 or a 404.

Inspecting your routes

The artisan command php artisan route:list prints every registered route with its verb, URI, name and action. Useful flags: --path=posts filters by URI, --name=posts by name, --method=GET by verb, and --except-vendor hides routes added by packages. When a route "does not work", this is the first command to run: it shows what actually got registered.

A router in plain PHP

The next example imitates the core of a router: it compiles and {param?} placeholders into regular expressions, honors constraints, picks a route by verb and path, and answers 404 or 405 when nothing fits. Real Laravel does this with Symfony's routing component and caching, so the code differs, but the behavior is the same idea.

PHP A mini router with parameters and constraints

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.

Look at /users/abc: the constraint rejects it, so the router reports 404 rather than calling your closure. And GET /posts gets a 405 because the path exists but only for POST. Laravel behaves the same way and also adds an Allow header to its 405 response.

Named routes and URL generation

Now the other direction: from a name and parameters back to a URL. The stand-in below keeps a name table and a route() function that fills placeholders and appends extra values as a query string, and it prints a route:list-style table. The real helper additionally prefixes the app URL and URL-encodes values.

PHP Named routes, route() and a route:list table

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.

The last lines show a safety property worth copying in real code: a missing required parameter is an error you see immediately, not a broken link in production. Laravel throws a UrlGenerationException in the same situation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do web routes live in a standard Laravel 13 project?

    routes/web.php holds web routes; bootstrap/app.php registers it with withRouting(). Routes in it get the web middleware group (sessions, CSRF and so on).
  2. 2. What happens when a request matches a route's path but fails a where() constraint on a parameter?

    A failed constraint means the route does not match at all. If no other route matches, Laravel answers 404.
  3. 3. Why use named routes with the route() helper instead of writing URLs by hand?

    route('posts.show', ['post' => 42]) builds the URL from the route table. Change the URI once and every link follows.
  4. 4. How do you make a trailing route parameter optional?

    Write {name?} in the URI and a default such as ?string $name = null in the action, otherwise PHP complains about a missing argument.

Summary

  • Routes map an HTTP verb plus a URI to an action; web routes live in routes/web.php.
  • Use Route::get/post/put/patch/delete, match, any, view and redirect for the common cases.
  • captures a segment, {param?} makes a trailing one optional (with a default in the action).
  • where(), whereNumber() and friends reject bad segments early; they do not replace validation.
  • Name routes and build URLs with route(); extra values become the query string.
  • php artisan route:list shows what is really registered.

Next: Route Groups and Model Binding