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 schemas, resolve data with Eloquent, and handle common GraphQL tasks with built-in directives and extensibility. Docs at lighthouse-php.com. Note: repo planned to move to spawnia/lighthouse.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nuwave/lighthouse
    php artisan lighthouse:install
    

    This publishes the config file (config/lighthouse.php) and sets up the GraphQL route.

  2. Define a Schema: Create a GraphQL schema file (e.g., graphql/schema.graphql) with your types, queries, and mutations. Example:

    type User @model {
      id: ID!
      name: String
    }
    
    type Query {
      users: [User!]! @paginate
    }
    
  3. First Query: Use the built-in Playground or tools like Apollo Studio to test:

    query {
      users {
        id
        name
      }
    }
    

Key First Use Cases

  • Model-Based Types: Use @model to auto-generate resolvers for Eloquent models.
  • Pagination: Add @paginate to queries for automatic pagination support.
  • Mutations: Define @create, @update, and @delete directives for CRUD operations.

Implementation Patterns

Schema Design

  1. Modular Schema Files: Split schema into logical files (e.g., users.graphql, posts.graphql) and import them in schema.graphql:

    schema {
      query: Query
    }
    
    import "graphql/users.graphql"
    import "graphql/posts.graphql"
    
  2. Directives for Common Tasks:

    • Authentication: Use @auth to protect fields/mutations.
    • Authorization: Use @can with Laravel policies.
    • Validation: Use @validate for input validation (e.g., @validate(rule: "required|min:3")).
    • Relations: Use @hasMany, @belongsTo, etc., for Eloquent relations.
  3. Custom Resolvers: For complex logic, create a resolver class and reference it in the schema:

    type Query {
      customData: String @resolve(class: "App\\GraphQL\\Resolvers\\CustomDataResolver")
    }
    

Workflows

  1. Development Workflow:

    • Use php artisan lighthouse:print-schema to generate a schema file for IDE autocompletion.
    • Run php artisan lighthouse:ide-helper to generate PHP type hints.
  2. Testing:

    • Use Nuwave\Lighthouse\Testing\MocksGraphQL for testing GraphQL endpoints:
      public function test_users_query()
      {
          $response = $this->graphQL(['query' => '{ users { id name } }']);
          $response->assertSuccess();
      }
      
  3. Performance Optimization:

    • Enable Automatic Persisted Queries in config/lighthouse.php to cache parsed queries.
    • Use @lazyLoad for nested relations to defer loading until needed.

Integration Tips

  1. Laravel Features:

    • Events: Trigger Laravel events in resolvers using event(new ModelCreated($model)).
    • Notifications: Send notifications from mutations:
      type Mutation {
        sendNotification(email: String!): Boolean @create(class: "App\\GraphQL\\Mutations\\SendNotification")
      }
      
  2. Subscriptions:

    • Use @subscribe for real-time updates:
      type Subscription {
        newUser: User @subscribe(class: "App\\GraphQL\\Subscriptions\\NewUser")
      }
      
  3. Error Handling:

    • Customize error responses in config/lighthouse.php under error_handler.
    • Use @throws to document expected errors in the schema.

Gotchas and Tips

Common Pitfalls

  1. Schema Cache:

    • Clear the schema cache after changes:
      php artisan lighthouse:clear-schema-cache
      
    • Avoid manual cache clearing in production; use php artisan lighthouse:clear-schema-cache --env=production sparingly.
  2. N+1 Queries:

    • Always use @paginate or @eagerLoad for relations to avoid N+1 issues.
    • Example:
      type User {
        posts: [Post!]! @hasMany @paginate
      }
      
  3. Input Validation:

    • Ensure @validate directives are placed on input types, not fields directly:
      input CreateUserInput {
        name: String! @validate(rule: "required|min:3")
      }
      
  4. Mutations and Relations:

    • For nested mutations (e.g., @create on a HasOne relation), ensure the parent model exists or use @upsert:
      type User {
        profile: Profile @hasOne
      }
      
      type Mutation {
        createProfile(userId: ID!, data: CreateProfileInput!): Profile @create(class: "App\\GraphQL\\Mutations\\CreateProfile")
      }
      
  5. Directives Conflicts:

    • Built-in directives (e.g., @auth, @paginate) have priority. Avoid naming custom directives similarly.

Debugging Tips

  1. Query Complexity:

    • Enable complexity analysis in config/lighthouse.php to detect expensive queries:
      'query_complexity' => [
          'enabled' => true,
          'limit' => 1000,
      ],
      
  2. Logging:

    • Enable debug logging in config/lighthouse.php:
      'debug' => env('APP_DEBUG', false),
      
  3. Schema Validation:

    • Use php artisan lighthouse:validate to check for schema errors before deployment.

Advanced Tips

  1. Custom Directives:

    • Extend Lighthouse by creating custom directives. Example:
      use Nuwave\Lighthouse\Support\Contracts\Directive;
      
      class CustomDirective implements Directive
      {
          public function __invoke($rootValue, array $args, $context, array $variables)
          {
              // Custom logic
          }
      }
      
    • Register in config/lighthouse.php:
      'directives' => [
          'custom' => \App\GraphQL\Directives\CustomDirective::class,
      ],
      
  2. GraphQL Middleware:

    • Use Laravel middleware with GraphQL:
      use Nuwave\Lighthouse\Transport\Http\Middleware\GraphQLMiddleware;
      
      $router->middleware(GraphQLMiddleware::class)->group(function () {
          // Your routes
      });
      
  3. Federation:

    • Enable GraphQL Federation for microservices:
      'federation' => [
          'enabled' => true,
          'key' => env('LIGHTHOUSE_FEDERATION_KEY'),
      ],
      
  4. Performance:

    • Use file-based query cache for OPcache optimization:
      'cache' => [
          'schema' => 'file',
      ],
      
  5. Security:

    • Disable introspection in production:
      'introspection' => env('APP_DEBUG', false),
      
    • Use @auth and @can to restrict access:
      type Mutation {
        deleteUser(id: ID!): Boolean @auth @can(class: "App\\Policies\\UserPolicy", method: "delete")
      }
      
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.
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
zedmagdy/filament-business-hours