How to fix the error "Undefined property App\Repository ::$_em".

How to fix the error "Undefined property App\Repository ::$_em".


If you are working with Symfony and Doctrine, you may have encountered the error

Undefined property: App\Repository\UserRepository::$_em.

Congratulations, looks like your Doctrine-Bundle is updated to version 3.*. This error is due to the removal of the $_em property from the EntityRepository class.

In previous versions of Doctrine, you could access the EntityManager instance using the $_em property. But in Doctrine 3.*, this property has been removed.

To fix this error, you need to update your code to use the getEntityManager() method instead of the $_em property.

Here is an example of how you can update your code:

namespace App\Repository;

use App\Entity\User;

class UserRepository extends ServiceEntityRepository
    public function save(User $user): void
-        $this->_em->persist($user);
-        $this->_em->flush();
+        $this->getEntityManager()->persist($user);
+        $this->getEntityManager()->flush();

By making this change, you should be able to fix the error Undefined property: App\Repository ::$_em and continue working with Symfony and Doctrine.

I hope this helps! Let me know if you have any questions.