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 Orm Laravel Package

api-platform/doctrine-orm

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require api-platform/doctrine-orm
    

    Ensure api-platform/core is installed (this package extends its functionality).

  2. Basic Usage The package provides Doctrine ORM integration for API Platform, enabling seamless CRUD operations with Doctrine entities. No extra configuration is needed if you're already using API Platform with Doctrine.

  3. First Use Case

    • Define an entity with API Platform annotations/attributes:
      use ApiPlatform\Metadata\ApiResource;
      use Doctrine\ORM\Mapping as ORM;
      
      #[ApiResource]
      #[ORM\Entity]
      class Book
      {
          #[ORM\Id, ORM\GeneratedValue, ORM\Column]
          #[ApiPlatform\Metadata\Get]
          public ?int $id = null;
      
          #[ORM\Column]
          public string $title;
      }
      
    • Access endpoints like /api/books (auto-generated by API Platform).

Implementation Patterns

Common Workflows

  1. Standard CRUD Operations

    • API Platform auto-generates endpoints (GET, POST, PUT, DELETE) for annotated entities.
    • Example: Fetch all books:
      GET /api/books
      
  2. Customizing Operations

    • Override default operations via operation metadata:
      #[ApiResource(
          operations: [
              new Get(collection: false),
              new Post(
                  processor: BookPostProcessor::class,
                  validationContext: ['groups' => ['book_validation']]
              )
          ]
      )]
      
  3. Filtering & Pagination

    • Use Doctrine filters (e.g., DateFilter, BooleanFilter) via ApiPlatform\Doctrine\Orm\Filter\*.
    • Example: Filter active books:
      #[ApiResource(
          filters: [new BooleanFilter(field: 'isActive')]
      )]
      
  4. Serialization Groups

    • Control which fields are exposed via #[Groups]:
      use Symfony\Component\Serializer\Annotation\Groups;
      
      #[Groups(['book:read'])]
      public string $title;
      
  5. Event Listeners

    • Hook into lifecycle events (e.g., prePersist, postRemove) via Doctrine event subscribers or API Platform’s #[ApiResource] events:
      #[ApiResource(
          events: [
              'prePersist' => [BookEventSubscriber::class, 'prePersist']
          ]
      )]
      
  6. DQL & Native Queries

    • Use #[ApiResource] with collectionOperations for custom queries:
      #[ApiResource(
          collectionOperations: [
              new Get(
                  uriTemplate: '/books/active',
                  method: 'GET',
                  normalizationContext: ['groups' => ['book:read']],
                  requirements: ['active' => '1'],
                  controller: BookController::class,
                  read: false
              )
          ]
      )]
      

Gotchas and Tips

Pitfalls

  1. Circular References

    • Avoid infinite loops in serialization by using #[Groups] or #[MaxDepth]:
      #[MaxDepth(1)]
      public Author $author;
      
  2. Doctrine vs. API Platform State

    • API Platform uses ApiPlatform\Core\Serializer\SerializerContextBuilder, which may override Doctrine’s default serialization. Explicitly set serialization_context in operations if needed.
  3. Filter Conflicts

    • Doctrine filters (e.g., SearchFilter) may conflict with API Platform’s built-in filters. Ensure unique filter names or disable duplicates in config:
      # config/packages/api_platform.yaml
      api_platform:
          formats:
              jsonld:
                  mime_types: ['application/ld+json']
          doctrine:
              orm:
                  filters: ~ # Override or extend default filters
      
  4. Performance with Large Datasets

    • Pagination is auto-enabled, but for deep queries, use #[ApiResource(paginationItemsPerPage: 20)] or implement custom pagination.
  5. Validation Groups

    • Forgetting to specify validationContext in operations may lead to silent failures. Always define groups:
      new Post(validationContext: ['groups' => ['book_validation']])
      

Debugging Tips

  1. Enable API Platform Debug Toolbar

    • Install api-platform/core with debug mode:
      composer require api-platform/core --dev
      
    • Add to config/packages/dev/api_platform.yaml:
      api_platform:
          debug: true
      
  2. Check Serialization Context

    • Use dd($context) in a custom controller to inspect serialization groups, formats, or filters.
  3. Doctrine Query Logging

    • Enable SQL logging in config/packages/dev/doctrine.yaml:
      doctrine:
          dbal:
              logging: true
              profiling: true
      
  4. Common Errors

    • "No route found": Ensure #[ApiResource] is applied to the entity.
    • Validation errors: Verify validationContext groups exist in your validator constraints.
    • Serialization issues: Check for missing #[Groups] or circular references.

Extension Points

  1. Custom Controllers

    • Override default controllers for complex logic:
      #[ApiResource(
          collectionOperations: [
              new Get(controller: CustomBookController::class)
          ]
      )]
      
  2. Dynamic Metadata

    • Use ApiPlatform\Metadata\Factory\MetadataFactoryInterface to dynamically generate resource metadata.
  3. Event Subscribers

    • Extend functionality via Doctrine events or API Platform’s #[ApiResource] events:
      #[ApiResource(
          events: [
              'postPersist' => [BookSubscriber::class, 'onPostPersist']
          ]
      )]
      
  4. Custom Serializers/Deserializers

    • Implement Symfony\Component\Serializer\Normalizer\NormalizerInterface or DenormalizerInterface for custom logic.
  5. Hybrid APIs

    • Combine with API Platform’s GraphQlResource for GraphQL support alongside REST.
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.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat