Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Doctrine Bundle Laravel Package

doctrine/doctrine-bundle

Symfony bundle integrating Doctrine DBAL and ORM. Provides database abstraction, schema tools, and an object-relational mapper with DQL for powerful queries, plus configuration and tooling that fits the Symfony ecosystem.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require doctrine/doctrine-bundle
    

    Add to config/bundles.php:

    return [
        Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
    ];
    
  2. Configuration: Define database connection in config/packages/doctrine.yaml:

    doctrine:
        dbal:
            url: '%env(DATABASE_URL)%'
        orm:
            auto_generate_proxy_classes: true
            naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
            auto_mapping: true
    
  3. First Use Case: Create an entity (src/Entity/Post.php):

    namespace App\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity]
    class Post
    {
        #[ORM\Id, ORM\GeneratedValue, ORM\Column]
        private ?int $id = null;
    
        #[ORM\Column(length: 255)]
        private string $title;
    }
    

    Run migrations:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    

Key Commands

  • doctrine:schema:update --dump-sql (Preview SQL)
  • doctrine:entity:generate (Generate entities from DB)
  • doctrine:query:sql (Run raw SQL)

Implementation Patterns

Core Workflows

1. Entity Management

  • CRUD Operations:
    $entityManager = $this->getDoctrine()->getManager();
    $post = new Post();
    $post->setTitle('Hello Doctrine');
    $entityManager->persist($post);
    $entityManager->flush();
    
  • Repository Pattern:
    $posts = $entityManager->getRepository(Post::class)->findAll();
    

2. Querying with DQL

$query = $entityManager->createQuery(
    'SELECT p FROM App\Entity\Post p WHERE p.title LIKE :title'
)->setParameter('title', '%Doctrine%');
$results = $query->getResult();

3. Migrations

  • Generate migration:
    php bin/console make:migration
    
  • Execute:
    php bin/console doctrine:migrations:migrate
    

4. Custom DQL Functions

# config/packages/doctrine.yaml
doctrine:
    orm:
        dql:
            string_functions:
                CONCAT: DoctrineExtensions\Query\Mysql\StringFunctions\MysqlConcat

5. Event Listeners/Subscribers

// src/EventListener/PostListener.php
namespace App\EventListener;

use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;

class PostListener implements EventSubscriberInterface
{
    public function prePersist(LifecycleEventArgs $args): void
    {
        $post = $args->getObject();
        $post->setCreatedAt(new \DateTime());
    }
}

Register in services.yaml:

services:
    App\EventListener\PostListener:
        tags:
            - { name: doctrine.event_subscriber }

Integration Tips

1. Symfony Forms + Doctrine

use Symfony\Bridge\Doctrine\Form\Type\EntityType;

$builder->add('author', EntityType::class, [
    'class' => User::class,
    'choice_label' => 'username',
]);

2. API Platform Integration

# config/packages/api_platform.yaml
api_platform:
    formats:
        jsonld:
            mime_types: ['application/ld+json']
    patch_formats:
        json: ['application/merge-patch+json']
    swagger:
        versions: [3]

3. Doctrine Extensions

composer require gedmo/doctrine-extensions

Configure in doctrine.yaml:

gedmo_listener:
    flushable: true

4. Custom Entity Managers

# config/packages/doctrine.yaml
doctrine:
    dbal:
        connections:
            default:
                url: '%env(DATABASE_URL)%'
            read_replica:
                url: '%env(READ_REPLICA_URL)%'
    orm:
        entity_managers:
            default:
                connection: default
                mappings:
                    App:
                        is_bundle: false
                        dir: '%kernel.project_dir%/src/Entity'
                        prefix: 'App\Entity'
                        alias: App
            read_only:
                connection: read_replica
                mappings:
                    App:
                        is_bundle: false
                        dir: '%kernel.project_dir%/src/Entity'
                        prefix: 'App\Entity'
                        alias: App

Gotchas and Tips

Common Pitfalls

1. Proxy Generation Issues

  • Symptom: Class 'App\Entity\Proxy\__CG__Post' not found
  • Fix:
    php bin/console doctrine:cache:clear-metadata
    php bin/console cache:clear
    
  • Prevention: Ensure auto_generate_proxy_classes is true and proxy_dir is writable.

2. Case-Sensitive Schema Problems

  • Symptom: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.post' doesn't exist
  • Fix: Configure naming_strategy in doctrine.yaml:
    doctrine:
        orm:
            naming_strategy: doctrine.orm.naming_strategy.underscore
    

3. Circular References in Entities

  • Symptom: Cannot determine table name for class "App\Entity\User" because its metadata is not yet loaded.
  • Fix: Use lazy: true in associations:
    #[ORM\ManyToOne(targetEntity: Post::class, inversedBy: 'authors', lazy: true)]
    

4. Migration Conflicts

  • Symptom: There are some new migrations, but you already have migrations in database.
  • Fix:
    php bin/console doctrine:migrations:execute --down --dry-run
    php bin/console doctrine:migrations:migrate
    

5. Event Subscriber Not Triggering

  • Symptom: Listener methods not called.
  • Fix: Ensure the service is tagged correctly:
    tags:
        - { name: doctrine.event_subscriber, connection: default }
    

Debugging Tips

1. Enable SQL Logging

# config/packages/dev/doctrine.yaml
doctrine:
    dbal:
        logging: true
        profiling: true

View logs in var/log/dev.log.

2. Use the Debug Toolbar

Install symfony/profiler-pack and enable:

# config/packages/dev/doctrine.yaml
framework:
    profiler: { only_exceptions: false }

3. DQL Query Debugging

$query = $entityManager->createQuery('SELECT p FROM App\Entity\Post p');
dump($query->getSQL()); // Raw SQL
dump($query->getParameters()); // Parameters

4. Schema Validation

php bin/console doctrine:schema:validate

Configuration Quirks

1. Auto-Mapping Deprecations

  • Issue: auto_mapping options like controller_resolver are deprecated.
  • Fix: Use explicit mappings configuration:
    doctrine:
        orm:
            auto_mapping: false
            mappings:
                App:
                  is_bundle: false
                  dir: '%kernel.project_dir%/src/Entity'
                  prefix: 'App\Entity'
                  alias: App
    

2. XML Mapping Issues

  • Symptom: Invalid XML mapping file
  • Fix: Ensure enable_xsd_validation is true and XSD schemas are valid:
    doctrine:
        orm:
            xml_validation: true
    

3. Connection Options

  • Symptom: Connection failures with use_savepoints or disable_type_comments.
  • Fix: Remove deprecated options (e.g., use_savepoints was removed in v3.0.0).

Extension Points

1. Custom Query Builders

namespace App\Doctrine;

use Doctrine\ORM\Query\QueryBuilder;

class Post
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle