Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 62 ยท Routing and Controllers

Route Parameters and Requirements

Learn Symfony route placeholders, regex requirements, optional parameters, backed enums and automatic entity loading with #[MapEntity], with a runnable router.

Most useful URLs contain variable parts: a post slug, a numeric id, a page number, a year and a month. In Symfony you write these as placeholders in curly braces, and the matched text arrives in your controller as an argument. This lesson covers the whole story: how placeholders match, how to restrict them with regular expressions, how to make them optional, and how Symfony can turn them into backed enums and Doctrine entities before your controller even runs.

The real routing code is shown read-only. The runnable parts are stand-ins: a tiny router that compiles paths into regular expressions (the same idea the real Routing component uses), and a small argument resolver that converts raw strings into enums and objects.

Placeholders

A placeholder is a name inside braces. It matches one or more characters up to the next /, and the value is passed to the controller argument with the same name:

PHP
// real Symfony, read-only
#[Route('/blog/{slug}', name: 'blog_show', methods: ['GET'])]
public function show(string $slug): Response
{
    return new Response('Post: ' . $slug);
}

A request for /blog/hello-world calls show('hello-world'). Matching is by name, not by position, so the order of controller arguments does not matter, and a controller may ignore a placeholder it does not need.

By default a placeholder matches [^/]+: anything except a slash. That is rarely what you really want. /blog/{id} would also match /blog/banana, and a controller declared as int $id would then fail with a type error instead of a clean 404. Requirements fix that.

Requirements

A requirement is a regular expression a placeholder must satisfy. If it does not match, the route is skipped and the next route is tried (and if nothing matches, the user gets a normal 404). There are three ways to write one:

PHP
// real Symfony, read-only
use Symfony\Component\Routing\Requirement\Requirement;

// 1. The requirements option
#[Route('/post/{id}', name: 'post_show', requirements: ['id' => '\d+'])]

// 2. Inline, inside the placeholder
#[Route('/post/{id<\d+>}', name: 'post_show')]

// 3. A ready-made constant
#[Route('/post/{id}', name: 'post_show', requirements: ['id' => Requirement::DIGITS])]

The Requirement class has constants for common patterns such as DIGITS, UUID and CATCH_ALL (which allows slashes, for paths like /files/images/2025/cat.png). Prefer these constants over copying regexes between routes.

Remember that PHP single-quoted strings keep \d as written, so '\d+' is the regular expression \d+.

Optional parameters and defaults

Give a placeholder a default and it becomes optional. Again there are two spellings:

PHP
// real Symfony, read-only
#[Route('/blog/{page}', name: 'blog_list', requirements: ['page' => '\d+'], defaults: ['page' => 1])]
#[Route('/blog/{page<\d+>?1}', name: 'blog_list')]   // same thing, inline
public function list(int $page = 1): Response { /* ... */ }

Both match /blog (page = 1) and /blog/3 (page = 3). Only the last placeholders of a path can be optional in a useful way: once a placeholder is optional, every placeholder after it must be optional too, otherwise Symfony could not tell which one is missing.

Two special placeholder names have built-in meaning: (the response format, such as html or json) and (the language, which Symfony also stores on the request). You will meet both in later lessons.

flowchart LR
    U["/archive/2025/07"] --> M["Match path pieces<br/>against route regex"]
    M --> R{"Requirements<br/>satisfied?"}
    R -- yes --> P["Parameters: year=2025, month=07"]
    R -- no --> N["Try next route"]
    N --> X["Nothing matched: 404"]
    P --> C["Argument resolvers<br/>(int, enum, entity)"]
    C --> K["Controller call"]

A path is matched against the compiled route; only after requirements pass do argument resolvers convert the raw strings into the types the controller asked for.

A router that compiles placeholders

This stand-in understands inline requirements ({id<\d+>}), defaults ({page<\d+>?1}) and the requirements array. It turns each path into a regular expression, then matches several URLs so you can see which ones pass.

PHP Compiling placeholders into regular expressions (stand-in)

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 /post/banana and /archive/25/7: both are rejected because of their requirements, and /blog matches with the default page filled in.

Enums as parameters

If a controller argument is typed with a backed enum, Symfony converts the placeholder text into the enum case with tryFrom(). An unknown value produces a 404, which is exactly the right answer for /posts/archived-ish:

PHP
// real Symfony, read-only
enum PostStatus: string
{
    case Draft = 'draft';
    case Published = 'published';
}

#[Route('/admin/posts/{status}', name: 'admin_posts_by_status')]
public function byStatus(PostStatus $status): Response
{
    // $status is PostStatus::Draft or PostStatus::Published; anything else never gets here
}

You can still add a requirement such as 'status' => 'draft|published' so the route does not even match for other values, which helps when another route could take that URL.

Entities from placeholders with #[MapEntity]

Loading a record by id is so common that Symfony does it for you. If Doctrine is installed and a controller argument is type-hinted with an entity class, Symfony looks the entity up by the placeholder and answers 404 when it does not exist:

PHP
// real Symfony, read-only
#[Route('/post/{id}', name: 'post_show', requirements: ['id' => '\d+'])]
public function show(Post $post): Response
{
    // $post is already loaded; a missing row means a 404 was sent automatically
}

For anything else, add #[MapEntity] to say how to find the object:

PHP
// real Symfony, read-only
use Symfony\Bridge\Doctrine\Attribute\MapEntity;

#[Route('/blog/{slug}', name: 'blog_show')]
public function show(
    #[MapEntity(mapping: ['slug' => 'slug'])] Post $post,
): Response { /* ... */ }

#[Route('/blog/{category}/{slug}', name: 'blog_in_category')]
public function inCategory(
    #[MapEntity(expr: 'repository.findOneByCategoryAndSlug(category, slug)')] Post $post,
): Response { /* ... */ }

mapping links route placeholders to entity fields, and expr runs an expression against the repository when a simple lookup is not enough. Databases come later in the tutorial; for now it is enough to understand what is going on, which the next stand-in shows with an in-memory "repository".

PHP Resolving enums and entities before the controller runs (stand-in)

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 unknown enum value and the missing post both end in a 404 before any controller code runs. That is the biggest benefit of resolvers: your controller can assume it received valid, ready-to-use objects.

Practical advice

  • Always add a requirement to numeric placeholders so /post/banana is a 404 and not a type error.
  • Do not use for public URLs if guessable ids are a problem; slugs or UUIDs are alternatives, and Requirement::UUID helps.
  • Keep optional parameters at the end of the path and rely on defaults instead of duplicating routes.
  • Run php bin/console debug:router post_show to see the compiled regex and the requirements Symfony actually applies.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an unrestricted placeholder like {slug} match by default?

    The default pattern is [^/]+, one or more characters up to the next slash. Add a requirement to restrict it or to allow slashes.
  2. 2. Which route path makes page optional with a default of 1 and only digits allowed?

    Inline syntax puts the requirement in angle brackets and the default after a question mark, so {page<\d+>?1} is equivalent to a requirements entry plus a defaults entry.
  3. 3. A controller argument typed with a backed enum receives a value the enum does not contain. What does Symfony do?

    Symfony converts the placeholder with tryFrom() and sends a 404 for unknown values.
  4. 4. When do you need #[MapEntity] instead of just type-hinting the entity?

    The {id} lookup is automatic. For other fields use mapping, and for complex lookups use expr.

Summary

  • placeholders match up to the next slash and are passed to the controller argument with the same name.
  • Requirements (the requirements option, inline {id<\d+>}, or Requirement::DIGITS) decide whether a route matches at all.
  • Defaults make placeholders optional; keep optional ones at the end.
  • Backed enums are resolved with tryFrom() and unknown values give a 404.
  • Doctrine entities load automatically by ; #[MapEntity] handles slugs and custom lookups.

Next up: Generating URLs.