How to Pass Extra Information from a Route to a Controller
Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.1 (the current stable version).
Parameters inside the defaults
collection don't necessarily have to match
a placeholder in the route path
. In fact, you can use the defaults
array to specify extra parameters that will then be accessible as arguments
to your controller, and as attributes of the Request
object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route(name="blog_")
*/
class BlogController
{
/**
* @Route("/blog/{page}", name="index", defaults={"page": 1, "title": "Hello world!"})
*/
public function index($page)
{
// ...
}
}
# config/routes.yaml
blog:
path: /blog/{page}
controller: App\Controller\BlogController::index
defaults:
page: 1
title: "Hello world!"
Now, you can access this extra parameter in your controller, as an argument to the controller method:
1 2 3 4
public function indexAction($page, $title)
{
// ...
}
Alternatively, the title could be accessed through the Request
object:
1 2 3 4 5 6 7 8
use Symfony\Component\HttpFoundation\Request;
public function indexAction(Request $request, $page)
{
$title = $request->attributes->get('title');
// ...
}
As you can see, the $title
variable was never defined inside the route
path, but you can still access its value from inside your controller, through
the method's argument, or from the Request
object's attributes
bag.