Make Route Available Based on Query Parameter in Symfony 8

Make Route Available Based on Query Parameter in Symfony 8

Modern web applications often require specific control over which endpoints are reachable under certain conditions. Rather than modifying controller logic or duplicating code, Symfony enables conditional routing using expressions. This tutorial demonstrates how to make route available based on query parameter in Symfony 8 application.

Symfony routing system includes a condition attribute that can evaluate expressions to determine whether a route should be matched. By utilizing request data, such as query parameters, we can selectively enable endpoints. This method is useful for debugging tools, feature previews, or experimental functionality that should only be active under specific requests.

Imagine we want a feature route to be accessible only when the URL includes a specific query parameter. Here, we can use request.query to check for the presence of the parameter. In the following example, the /feature route will only be active if ?preview=1 is present; otherwise, it will remain unavailable.

src/Controller/FeatureController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class FeatureController
{
    #[Route('/feature', name: 'feature', condition: "request.query.get('preview') === '1'")]
    public function index(): Response
    {
        return new Response();
    }
}

config/routes.yaml

feature:
    path: /feature
    controller: App\Controller\FeatureController::index
    condition: "request.query.get('preview') === '1'"

Leave a Comment

Cancel reply

Your email address will not be published.