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

Graphql Laravel Package

api-platform/graphql

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require api-platform/graphql
    

    Ensure your project uses API Platform (api-platform/core) and Symfony Flex (or manually configure autoloading).

  2. Enable the Bundle Add to config/bundles.php:

    return [
        // ...
        ApiPlatform\GraphQL\Bundle\GraphQLBundle::class => ['all' => true],
    ];
    
  3. First Query Configure GraphQL endpoint in config/packages/api_platform.yaml:

    api_platform:
        formats:
            jsonld: ['application/ld+json']
            json: ['application/json']
            html: ['text/html']
            graphql: ['application/graphql']
    

    Test with a simple query at /graphql:

    query {
      users {
        id
        name
      }
    }
    
  4. Key Files to Review

    • config/packages/api_platform.yaml (GraphQL settings)
    • src/Entity/ (Your API resources)
    • src/GraphQL/ (Custom resolvers, if needed)

Implementation Patterns

1. Schema Generation

  • Automatic Schema: The package auto-generates a GraphQL schema from your API Platform resources (entities with @ApiResource).
  • Customization: Override schema generation by extending ApiPlatform\GraphQL\Generator\SchemaGenerator or using decorators.

2. Querying Data

  • Standard Queries: Use entity names (pluralized) as root query types:
    query {
      users { id name }
      posts { title content }
    }
    
  • Filters: Leverage API Platform’s built-in filters (e.g., ?filter[where][name][contains]=John → GraphQL equivalent):
    query {
      users(filter: { name: { contains: "John" } }) { id name }
    }
    

3. Mutations

  • Create/Update/Delete: Use create<Entity>, update<Entity>, delete<Entity> mutations:
    mutation {
      createUser(input: { name: "Alice", email: "alice@example.com" }) {
        id name
      }
    }
    
  • Input Types: Auto-generated from your entity fields. Customize via @GraphQL\Query/@GraphQL\Mutation attributes.

4. Relationships

  • Nested Queries: Fetch related data directly:
    query {
      posts {
        title
        author { name }
      }
    }
    
  • Pagination: Use first, last, after, before arguments:
    query {
      users(first: 10) { id name }
    }
    

5. Custom Resolvers

  • Override Logic: Create a resolver class (e.g., src/GraphQL/Query/UserResolver) and tag it:
    #[Query]
    class UserResolver {
        #[Resolve(name: "User")]
        public function resolve(UserInterface $user): array {
            return [
                'id' => $user->getId(),
                'customField' => $user->getCustomField(),
            ];
        }
    }
    
  • Dependencies: Inject services via constructor (e.g., UserRepository, Serializer).

6. Integration with API Platform

  • Same Entities: Use existing API Platform entities (no duplication).
  • Serialization Groups: Control output fields via @Groups:
    #[ApiResource(
        normalizationContext: ['groups' => ['user:read']]
    )]
    class User { ... }
    
    query {
      users { id name } # Only fields in 'user:read' group
    }
    

7. Authentication/Authorization

  • Built-in Support: Use API Platform’s security (e.g., @IsGranted):
    #[Query]
    class AdminQuery {
        #[Resolve(name: "adminDashboard")]
        #[IsGranted("ROLE_ADMIN")]
        public function dashboard(): array { ... }
    }
    
  • GraphQL Context: Access user/scope via $context in resolvers:
    public function __invoke($root, array $args, $context) {
        $user = $context['security']->getUser();
    }
    

Gotchas and Tips

1. Schema Caching

  • Issue: Schema regenerates on every request by default (slow for large APIs).
  • Fix: Enable caching in config/packages/api_platform.yaml:
    api_platform_graphql:
        schema_cache_enabled: true
        schema_cache_ttl: 3600 # 1 hour
    
  • Clear Cache: Run php bin/console cache:clear after schema changes.

2. N+1 Query Problem

  • Issue: Nested queries trigger N+1 database queries.
  • Fix: Use #[ApiResource(denormalizationContext: ['groups' => ['user:write']])] and eager-load relationships:
    query {
      users { id posts { title } } # Loads posts eagerly if configured
    }
    

3. Custom Scalar Types

  • Issue: Need to handle non-standard types (e.g., DateTime, Upload).
  • Fix: Register custom scalars in config/packages/api_platform_graphql.yaml:
    api_platform_graphql:
        custom_scalars:
            DateTime: 'App\GraphQL\Scalar\DateTimeScalar'
    

4. Mutation Input Validation

  • Issue: Mutations may fail silently with validation errors.
  • Fix: Use @Assert constraints in entities or custom resolvers:
    use Symfony\Component\Validator\Constraints as Assert;
    
    #[Assert\NotBlank]
    private ?string $email;
    
    Errors appear in GraphQL response under errors.

5. Performance Tips

  • Pagination: Always paginate queries to avoid over-fetching:
    query {
      users(first: 20) { id name }
    }
    
  • Field Selection: Explicitly list fields to reduce payload size:
    query {
      users { id } # Only fetch IDs
    }
    

6. Debugging

  • GraphQL Playground: Enable at /graphql for interactive testing.
  • Logs: Check var/log/dev.log for schema generation errors.
  • Doctrine Events: Listen to api_platform.graphql.schema.generated to debug schema issues:
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use ApiPlatform\GraphQL\Event\SchemaGeneratedEvent;
    
    class SchemaSubscriber implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [SchemaGeneratedEvent::NAME => 'onSchemaGenerated'];
        }
    
        public function onSchemaGenerated(SchemaGeneratedEvent $event) {
            // Dump schema for debugging
            file_put_contents('schema.graphql', $event->getSchema()->__toString());
        }
    }
    

7. Extending the Schema

  • Add Custom Types: Create a src/GraphQL/Type/ directory and use @GraphQL\Type:
    #[Type]
    class CustomType {
        #[Field]
        public function field(): string { return "value"; }
    }
    
  • Union Types: Define unions for polymorphic entities:
    #[UnionType(name: "Content")]
    class ContentUnion { ... }
    

8. Deprecation Warnings

  • Issue: API Platform may deprecate features (e.g., jsonld format).
  • Fix: Monitor API Platform changelog and update dependencies:
    composer update api-platform/core api-platform/graphql
    

9. Testing

  • Unit Tests: Mock the schema generator:
    use ApiPlatform\GraphQL\Generator\SchemaGenerator;
    
    $schemaGenerator = new SchemaGenerator($entityManager);
    $schema = $schemaGenerator->generateSchema();
    
  • Integration Tests: Use GraphQLClient (e.g., webonyx/graphql-php):
    $client = new GraphQLClient('http://localhost/graphql');
    $result = $client->query('{ users { id } }');
    

10. Common Pitfalls

  • Circular References: Avoid infinite loops in relationships (e.g., User → Post → User). Fix: Use @MaxDepth or @ApiResource(iri="...") to break cycles.
  • Case Sensitivity: GraphQL queries are case-sensitive (e.g., users vs Users).
  • Null Handling: GraphQL returns null for missing fields; use @GraphQL\Deprecated to mark obsolete fields.
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky