Skip to content

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

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

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

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

pauljura opened this issue Feb 5, 2025 · 0 comments
Labels
Doctrine hasPR A Pull Request has already been submitted for this issue.

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

@javiereguiluz javiereguiluz added Doctrine hasPR A Pull Request has already been submitted for this issue. labels Jun 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Doctrine hasPR A Pull Request has already been submitted for this issue.
Projects
None yet
Development

No branches or pull requests

2 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy