Symfony\Component\Routing\Exception\MissingMandatoryParametersException:生成路由“user_profile”的 URL 缺少某些必需参数(“id”),位于 /var/www/app/src/Controller/UserController.php 第 34 行
Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("id") to generate a URL for route "user_profile" in /var/www/app/src/Controller/UserController.php:34
ID: php/symfony-route-parameter-constraint-violation
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| symfony 6.4 | active | — | — | — |
| symfony 7.0 | active | — | — | — |
| symfony 7.1 | active | — | — | — |
| php 8.2 | active | — | — | — |
根因分析
当使用 `$router->generate()` 或 Twig 的 `path()` 函数从路由定义生成 URL 时,未提供一个或多个必需的路由参数(在路由路径中定义)。
English
When generating a URL from a route definition using `$router->generate()` or Twig's `path()` function, one or more required route parameters (defined in the route path) are not provided.
官方文档
https://symfony.com/doc/current/routing.html#generating-urls解决方案
-
Pass the missing parameter when generating the URL: `$url = $this->generateUrl('user_profile', ['id' => $user->getId()]);` or in Twig: `{{ path('user_profile', {id: user.id}) }}`. -
If the parameter is optional, make it optional in the route definition by adding a default value: `#[Route('/user/{id}', defaults: ['id' => null])]`.
无效尝试
常见但无效的做法:
-
Clearing the Symfony cache with `php bin/console cache:clear`
90% 失败
The cache clear does not fix the missing parameter issue; it only refreshes the route metadata, but the call site still lacks the required argument.
-
Adding a default value for the parameter in the route definition without providing it at generation time
60% 失败
If the parameter is in the route path (e.g., `/user/{id}`), it is mandatory unless a default is set in the route definition; adding a default may work but can lead to incorrect URLs if the default is used unintentionally.