Weave 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 Mapper Laravel Package

arthem/graphql-mapper

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require arthem/graphql-mapper
    

    Ensure webonyx/graphql-php is also installed (dependency).

  2. Define a Schema Mapping File Create a YAML file (e.g., graphql/schema.yml) to map your Eloquent models to GraphQL types. Example:

    types:
        User:
            model: App\Models\User
            fields:
                id:
                    type: ID!
                name:
                    type: String
                email:
                    type: String
    
  3. Load the Schema in Laravel Register the schema loader in a service provider (e.g., GraphQLServiceProvider):

    use Arthem\GraphQLMapper\Loader\YamlLoader;
    use Arthem\GraphQLMapper\Schema\Builder;
    
    public function boot()
    {
        $loader = new YamlLoader(__DIR__.'/../config/graphql/schema.yml');
        $schema = Builder::build($loader->load());
        $this->app->singleton('graphql.schema', function () use ($schema) {
            return $schema;
        });
    }
    
  4. First Use Case: Query a Model Use the schema in a GraphQL endpoint (e.g., via graphql-php's GraphQLServer):

    $query = '
        query {
            users {
                id
                name
            }
        }
    ';
    $result = $this->app->make('graphql.schema')->executeQuery($query);
    

Implementation Patterns

Workflows

  1. Model-Driven Schema Definition

    • Define GraphQL types directly from Eloquent models using YAML/JSON/array configs.
    • Example: Map a Post model with relationships:
      types:
          Post:
              model: App\Models\Post
              fields:
                  id: { type: ID! }
                  title: { type: String! }
                  author:
                      type: User
                      resolve:
                          handler: doctrine
                          field: user
      
  2. Resolver Handlers

    • Use built-in handlers (doctrine, eloquent) or custom resolvers for complex logic:
      fields:
          fullName:
              type: String
              resolve:
                  handler: custom
                  class: App\GraphQL\Resolvers\FullNameResolver
      
  3. Query/Mutation Generation

    • Dynamically generate queries for CRUD operations:
      // Fetch a user by ID
      $query = $schema->createQuery('users', ['id' => 1]);
      $result = $schema->executeQuery($query);
      
  4. Integration with Laravel Routes

    • Bind the schema to a route in routes/web.php:
      Route::post('/graphql', function () {
          return $this->app->make('graphql.schema')->executeQuery(
              request()->input('query'),
              request()->input('variables', [])
          );
      });
      

Tips for Daily Use

  • Leverage Laravel’s Service Container: Bind the schema and resolvers as singletons for reuse.
  • Use Traits for Common Resolvers: Extend base resolvers for shared logic (e.g., pagination, authorization).
  • Validation: Validate YAML configs with SchemaValidator to catch misconfigurations early.
  • Caching: Cache the built schema in production to avoid rebuilding on every request.

Gotchas and Tips

Pitfalls

  1. Abandoned Package

    • The package is unmaintained (last release in 2016). Expect no updates or bug fixes.
    • Mitigation: Fork the repo and maintain it internally, or migrate to modern alternatives like graphql-php/graphql with custom mappers.
  2. YAML Configuration Quirks

    • Indentation Sensitivity: YAML must be perfectly indented; use a linter (e.g., yamllint).
    • Handler Mismatches: Ensure resolve.handler matches a registered resolver (e.g., doctrine requires Doctrine ORM).
    • Circular References: Avoid circular relationships (e.g., User -> Post -> User) without custom resolvers.
  3. Performance Issues

    • N+1 Queries: Resolvers like doctrine may trigger N+1 queries. Use eager loading or custom resolvers.
    • Schema Rebuilding: The schema is rebuilt on every request by default. Cache it in production:
      $schema = Builder::build($config, ['cache' => true]);
      
  4. Laravel-Specific Gotchas

    • Eloquent vs. Doctrine: The package assumes Doctrine by default. For Eloquent, use the eloquent handler or write custom resolvers.
    • Namespace Conflicts: Ensure model namespaces in YAML match Laravel’s autoloading (e.g., App\Models\User).

Debugging

  • Enable GraphQL Errors: Configure graphql-php to return detailed errors:
    $schema->setErrorFormatter(function ($e) {
        return [
            'message' => $e->getMessage(),
            'trace'   => $e->getTrace(),
        ];
    });
    
  • Log Resolver Calls: Add logging to resolvers to trace execution:
    class CustomResolver implements ResolverInterface {
        public function resolve($root, array $args, Schema $schema) {
            \Log::debug('Resolver called with args:', $args);
            // ...
        }
    }
    
  • Validate Schema: Use the SchemaValidator to check for syntax errors:
    $validator = new SchemaValidator();
    $errors = $validator->validate($config);
    

Extension Points

  1. Custom Resolvers

    • Implement Arthem\GraphQLMapper\Resolver\ResolverInterface for bespoke logic:
      class CustomResolver implements ResolverInterface {
          public function resolve($root, array $args, Schema $schema) {
              return $root->customAttribute;
          }
      }
      
    • Register in YAML:
      fields:
          customField:
              type: String
              resolve:
                  handler: custom
                  class: App\GraphQL\Resolvers\CustomResolver
      
  2. Dynamic Field Resolution

    • Use Arthem\GraphQLMapper\Field\DynamicField for runtime field resolution (e.g., conditional fields).
  3. Middleware Integration

    • Attach Laravel middleware to GraphQL requests via route middleware or a custom GraphQLServer wrapper.
  4. Testing

    • Mock the schema in tests:
      $schema = $this->app->make('graphql.schema');
      $result = $schema->executeQuery($query, [], [], ['mock' => true]);
      
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.
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus