[Symfony] Test if a Doctrine entity is already persisted in the database

Published on 2018-09-11 • Modified on 2018-09-23

This code is called from an action function of a Symfony 4.1 standard controller (extending Symfony\Bundle\FrameworkBundle\Controller\Controller):

<?php declare(strict_types=1);

namespace App\Controller\Snippet;

use App\Entity\Article;
use App\Entity\ArticleType;
use App\Entity\ArticleTypeRepository;
use Doctrine\Bundle\DoctrineBundle\Registry;

 * I am using a PHP trait in order to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Sf 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Sf <= 4.1)
 * Services are injected in the controller constructor.
trait Snippet2Trait
    public function snippet2(): void
        // Get doctrine manager (From a Symfony 4.2 controller)
        $doctrine = $this->getDoctrine();
        if (!$doctrine instanceof Registry) {
            throw new \RuntimeException("Houston, We've Got a Problem. 💥");

        $manager = $doctrine->getManager();
        $article = new Article(); // create a fresh Doctrine object
        $isPersisted = $manager->contains($article);
        var_dump($isPersisted); // returns false

        // Set minimum database constraints so the entity can be persisted
        $repo = $manager->getRepository(ArticleType::class);
        if (!$repo instanceof ArticleTypeRepository) {
            throw new \RuntimeException('Repo not found.');
        $manager->persist($article); // persist in database

        $isPersisted = $manager->contains($article);
        /** @noinspection ForgottenDebugOutputInspection */
        var_dump($isPersisted); // returns true

        // That's it! 😁

 Run this snippet  More on Stackoverflow