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

Lighthouse Laravel Package

nuwave/lighthouse

Lighthouse is a Laravel-first GraphQL server framework. Define your schema, wire resolvers, and handle common tasks like validation, auth, pagination, and Eloquent integration, with flexibility for custom GraphQL needs.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require nuwave/lighthouse
   php artisan lighthouse:install

This generates a graphql route and config file (config/lighthouse.php).

  1. First Query: Define a basic schema in graphql/schema.graphql:

    type Query {
      hello: String
    }
    

    Create a resolver in app/GraphQL/Queries/Hello.php:

    namespace App\GraphQL\Queries;
    
    class Hello
    {
        public function __invoke($root, array $args)
        {
            return 'World';
        }
    }
    

    Test via GraphQL Playground (accessible at /graphql) with:

    query {
      hello
    }
    
  2. Key Files:

    • graphql/schema.graphql: Schema definition (SDL).
    • app/GraphQL/: Resolvers (auto-discovered via naming conventions).
    • config/lighthouse.php: Configuration (e.g., middleware, directives).

Implementation Patterns

1. Resolver Workflows

  • Naming Conventions:

    • Queries: app/GraphQL/Queries/{PascalCaseName}.php
    • Mutations: app/GraphQL/Mutations/{PascalCaseName}.php
    • Subscriptions: app/GraphQL/Subscriptions/{PascalCaseName}.php Example:
    // app/GraphQL/Queries/GetUser.php
    class GetUser {
        public function __invoke($root, array $args) {
            return User::find($args['id']);
        }
    }
    
  • Resolver Arguments: Use the $resolveInfo parameter for advanced use cases (e.g., client directives, field selection):

    public function __invoke($root, array $args, $context, \Nuwave\Lighthouse\Support\Contracts\ResolveInfo $resolveInfo) {
        $clientDirective = new \Nuwave\Lighthouse\ClientDirectives\ClientDirective('example');
        $arguments = $clientDirective->forField($resolveInfo);
        // ...
    }
    

2. Schema Organization

  • Modular Schema: Use #import in schema.graphql to split definitions across files:

    #import "types/user.graphql"
    #import "queries/posts.graphql"
    

    Load dynamically via SchemaStitcher:

    $stitcher = new \Nuwave\Lighthouse\Schema\Source\SchemaStitcher(__DIR__.'/graphql');
    return $stitcher->getSchemaString();
    
  • Dynamic Schema: Listen to BuildSchemaString event to inject schema parts at runtime:

    event(new \Nuwave\Lighthouse\Events\BuildSchemaString($schemaString));
    

3. Common Directives

  • @auth: Protect fields/queries:

    type Query {
        secret: String @auth
    }
    

    Configure in config/lighthouse.php:

    'directives' => [
        'auth' => \Nuwave\Lighthouse\Directives\AuthDirective::class,
    ],
    
  • @deprecated: Mark schema elements as deprecated:

    type Query {
        oldField: String @deprecated(reason: "Use newField instead")
    }
    

    Detect usage via:

    DetectDeprecatedUsage::handle(function (array $deprecations) {
        // Log or notify
    });
    

4. File Uploads

  • Schema Setup:
    scalar Upload @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Upload")
    type Mutation {
        uploadFile(file: Upload!): String
    }
    
  • Resolver:
    public function __invoke($root, array $args) {
        /** @var \Illuminate\Http\UploadedFile $file */
        $file = $args['file'];
        return $file->store('uploads');
    }
    
  • Client-Side: Use multipart/form-data with GraphQL multipart spec (e.g., Apollo Upload Client).

5. Performance

  • Batch Loading: Use loadMany in resolvers for N+1 queries:

    public function __invoke($root, array $args) {
        return User::whereIn('id', $args['ids'])->get();
    }
    

    Configure in config/lighthouse.php:

    'batch_loading' => true,
    
  • Caching: Cache resolvers or schema fragments:

    $cache = app(\Nuwave\Lighthouse\Support\Cache\Cache::class);
    $cache->remember('schema_fragment', 60, function () {
        return $this->buildSchemaFragment();
    });
    

Gotchas and Tips

Pitfalls

  1. Resolver Signature Mismatch:

    • Lighthouse expects resolvers to return null for missing data (not false or exceptions).
    • Example:
      public function __invoke($root, array $args) {
          return User::find($args['id']); // Returns null if not found
      }
      
  2. Circular Dependencies:

    • Avoid circular references in schema types (e.g., TypeA references TypeB, which references TypeA).
    • Use interfaces or abstract types to break cycles.
  3. Client Directives:

    • Directives like @skip/@include are client-side only. Server-side logic must handle multiple directive configurations per field (see docs).
  4. File Uploads:

    • Ensure X-Requested-With: XMLHttpRequest header is set if using CSRF middleware.
    • Test with multipart/form-data and the GraphQL multipart spec.
  5. Schema Validation:

    • Lighthouse validates schema syntax but may not catch logical errors (e.g., missing resolvers).
    • Use php artisan lighthouse:schema:validate to check for issues.

Debugging Tips

  1. Enable Debug Mode:

    'debug' => env('APP_DEBUG', false),
    
    • Logs queries, resolvers, and errors to storage/logs/lighthouse.log.
  2. Query Introspection:

    • Use the GraphQL Playground to inspect the schema:
      query {
        __schema {
          types {
            name
            fields {
              name
              type {
                name
              }
            }
          }
        }
      }
      
  3. Resolver Logging:

    • Add logging to resolvers:
      \Log::debug('Resolver args:', $args);
      
  4. Schema Diffing:

    • Compare schema versions using php artisan lighthouse:schema:diff.

Extension Points

  1. Custom Directives:

    • Extend built-in directives or create new ones:
      class CustomDirective extends \Nuwave\Lighthouse\Directives\BaseDirective {
          protected $config = [
              'auth' => \Nuwave\Lighthouse\Directives\AuthDirective::class,
              'custom' => \App\GraphQL\Directives\CustomDirective::class,
          ];
      }
      
  2. Middleware:

    • Add GraphQL-specific middleware:
      \Nuwave\Lighthouse\Transport\Http\Middleware\ValidateGraphQLRequest::class,
      \App\Http\Middleware\CheckUserRole::class,
      
  3. Type System:

    • Register custom scalars:
      $scalar = new \Nuwave\Lighthouse\Schema\Types\CustomScalarType('DateTime', function ($value) {
          return \Carbon\Carbon::parse($value);
      });
      $typeRegistry->mustBeRegistered($scalar);
      
  4. Event Listeners:

    • Hook into Lighthouse events (e.g., AfterResolveType, BeforeExecuteQuery):
      event(new \Nuwave\Lighthouse\Events\AfterResolveType($type, $result));
      

Configuration Quirks

  1. CORS:

    • Ensure CORS headers are set for GraphQL endpoints:
      'cors' => [
          'paths' => ['graphql', 'graphql/*'],
          'allowed_methods' => ['*'],
          'allowed_origins' => ['*'],
          'allowed_headers' => ['*'],
          'exposed_headers' => [],
          'max_age' => 0,
          'supports_credentials' => false,
      ],
      
  2. Depth Limit:

    • Prevent overly deep queries (default: 10):
      'query_depth_limit' => 15,
      
  3. Complexity Analysis:

    • Enable to detect expensive queries:
      'complexity' => [
          'enabled' => true,
          'limit'
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport