Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
pauljura opened this issue Feb 5, 2025 · 0 comments
Open

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

pauljura opened this issue Feb 5, 2025 · 0 comments

Comments

@pauljura
Copy link

pauljura commented Feb 5, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant