How do I check if object was found in a Doctrine2 repository? How do I check if object was found in a Doctrine2 repository? symfony symfony

How do I check if object was found in a Doctrine2 repository?


EntityRepository::find() method (which you use) returns an object, or null if the object couldn't be found in the database. All of the following conditions are valid:

if ($entity) {}if (null !== $entity) {}if ($entity instanceof Representative) {}

Choose one that suits your coding standards the best, and use it consistently.

If you don't need to create a new object if it's not found, better throw an exception and handle it appropriately.


How about this:

$product = $this->getDoctrine()        ->getRepository('AppBundle:Product')        ->find($id);    if (!$product) {        throw $this->createNotFoundException(            'No product found for id '.$id        );

Source: click me