Allow Slash Character in Route Parameter in Symfony 7

Allow Slash Character in Route Parameter in Symfony 7

In some applications, we may need to define a URL with parameter that can contain a slash / character. This character has special meaning because it is used to separate the different URL parts.

This tutorial explains how to allow slash character in route parameter in Symfony 7 application.

By default, Symfony framework allows having all characters in route parameters except a slash / character. If we want to allow this character to be part of a route parameter, we need to define the .+ expression in the parameter requirements.

src/Controller/PostController.php

<?php

namespace App\Controller;

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

class PostController
{
    #[Route('/post/{slug}', name: 'post_show', requirements: ['slug' => '.+'])]
    public function show(string $slug): Response
    {
        return new Response($slug);
    }
}

config/routes.yaml

post_show:
    path: /post/{slug}
    controller: App\Controller\PostController::show
    requirements:
        slug: .+

Leave a Comment

Cancel reply

Your email address will not be published.