Skip to content

How to indicate that an entity in a route is optional #20618

Closed
@pauljura

Description

@pauljura

Hi folks,

This section: https://symfony.com/doc/current/doctrine.html#automatically-fetching-objects-entityvalueresolver

The bundle uses the {id} from the route to query for the Product by the id column. If it's not found, a 404 page is generated.

I think this is missing an explanation of how to override the default 404 behaviour.

The solution is to indicate that the method parameter is optional, by inserting a question mark in front of the class name. Some example code might look like this:

class ProductController extends AbstractController
{
    #[Route('/product/{id}')]
    public function show(?Product $product): Response
    {
        if ($product instanceof Product) {
            // use the Product!
            // ...
        } else {
            // your custom response
            // ...
        }
    }
}

I think this was documented at some point, because I know this works and I think I read it here, so I guess at some point this was removed. I think it's a useful feature to know about, so should be documented somewhere.

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    DoctrinehasPRA Pull Request has already been submitted for this issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions