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

Eloquent Graphql Laravel Package

optigov/eloquent-graphql

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require optigov/eloquent-graphql
    
  2. Annotate Models: Add @property docblocks to your Eloquent models to define GraphQL fields. Example:

    /**
     * @property int $id
     * @property string $name
     * @property-read \Carbon\Carbon $created_at
     */
    class Post {}
    
  3. Register Schema: Integrate the schema into your GraphQL server (e.g., webonyx/graphql-php):

    use EloquentGraphQL\Services\EloquentGraphQLService;
    
    $service = new EloquentGraphQLService();
    $schema = new Schema([
        'query' => $service->query()
            ->view(Post::class)
            ->all(Post::class)
            ->build(),
    ]);
    
  4. First Query: Query your annotated model directly:

    query {
      posts {
        id
        name
      }
    }
    

Where to Look First

  • Model Annotations: Focus on @property and @property-read docblocks in your Eloquent models.
  • Service Class: EloquentGraphQLService is the core class for schema generation.
  • README Examples: The package’s README provides clear examples for common use cases (e.g., relationships, pagination).

Implementation Patterns

Core Workflow

  1. Model Annotations:

    • Use @property for writable fields (e.g., name).
    • Use @property-read for read-only fields (e.g., created_at).
    • Support nested relationships (e.g., @property Author $author).
    • Arrays of models (e.g., @property Post[] $comments).
  2. Schema Registration:

    • Query Methods:
      • view(Model::class): Exposes a single model query (e.g., post(id: 1)).
      • all(Model::class): Exposes a collection query (e.g., posts).
    • Mutation Methods (if supported):
      • create(Model::class), update(Model::class), delete(Model::class).
  3. Relationship Handling:

    • Automatic resolution of belongsTo, hasMany, belongsToMany, etc., via annotations.
    • Example:
      /**
       * @property Author $author
       * @property Post[] $comments
       */
      class Post {}
      
      Query:
      query {
        post(id: 1) {
          author { name }
          comments { title }
        }
      }
      
  4. Pagination and Filtering:

    • Supports cursor-based pagination (e.g., posts(first: 10)).
    • Filtering via GraphQL arguments (e.g., posts(where: { name_contains: "Laravel" })).
    • Ordering (e.g., posts(orderBy: { field: "created_at", direction: DESC })).
  5. Integration with Laravel:

    • Works seamlessly with Laravel’s Eloquent ORM.
    • Leverage Laravel’s query builder for complex filtering (e.g., whereHas, orWhere).

Advanced Patterns

  • Custom Resolvers: Override default resolvers by extending EloquentGraphQLService or using GraphQL’s resolver hooks. Example:

    $service->query()->view(Post::class)->customResolver('customField', fn($root) => $root->title . ' (Custom)');
    
  • Input Types: Automatically generates input types for mutations (e.g., CreatePostInput). Customize via annotations:

    /**
     * @property-write string $name
     * @property-write string $content
     */
    class Post {}
    
  • Performance: Use with() in annotations to eager-load relationships:

    /**
     * @property Author $author
     * @property-read Post[] $comments with="user"
     */
    class Post {}
    

Gotchas and Tips

Pitfalls

  1. Annotation Syntax:

    • Forgetting @property-read for non-writable fields (e.g., timestamps) will cause GraphQL errors.
    • Incorrect relationship annotations (e.g., @property Author[] $authors when it’s a belongsTo) may break queries.
    • Fix: Double-check annotations against your model’s actual relationships.
  2. Circular References:

    • Bidirectional relationships (e.g., PostAuthor with hasMany/belongsTo) can cause infinite recursion.
    • Fix: Use @property-read and limit depth in queries or add @ignore to one side:
      /**
       * @property-read Author $author @ignore
       */
      class Post {}
      
  3. Pagination Quirks:

    • Default pagination might not align with your frontend’s expectations (e.g., first vs. last).
    • Fix: Customize pagination via the service:
      $service->query()->all(Post::class)->paginate(20, 'page');
      
  4. Mutation Limitations:

    • Mutations (e.g., create, update) may not be fully supported out of the box.
    • Fix: Extend the service or use GraphQL’s raw mutations for complex logic.
  5. Caching:

    • Schema regeneration on every request can be slow for large applications.
    • Fix: Cache the schema:
      $schema = Cache::remember('graphql.schema', now()->addHours(1), fn() => $schema);
      

Debugging Tips

  1. Schema Validation: Use GraphQL’s introspection to validate your schema:

    query {
      __schema {
        types {
          name
          fields {
            name
            type {
              name
            }
          }
        }
      }
    }
    
  2. Logs and Errors: Enable GraphQL error logging:

    $schema->setErrorHandler(function ($error) {
        Log::error($error->getMessage());
    });
    
  3. Annotation Validation: Run PHPStan or Psalm to catch annotation syntax errors early.

Extension Points

  1. Custom Directives: Add GraphQL directives to models for dynamic behavior:

    /**
     * @property string $name @directive("uppercase")
     */
    class Post {}
    

    Then implement the directive logic in the resolver.

  2. Plugin System: Extend EloquentGraphQLService to add custom logic:

    class CustomGraphQLService extends EloquentGraphQLService {
        public function customMethod(Model $model) {
            // Add custom GraphQL logic
        }
    }
    
  3. Hybrid Schemas: Combine with other GraphQL packages (e.g., rebing/graphql-laravel) for advanced features like subscriptions or custom scalars.

  4. Testing: Use Laravel’s HTTP tests to validate GraphQL queries:

    $response = $this->graphQL(['query' => '{ posts { id } }']);
    $response->assertJson(['data' => ['posts' => [...]]);
    
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.
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed