Lighthouse GraphQL Framework for Laravel

repository·master·Indexed 25 days ago

https://github.com/nuwave/lighthouse

Lighthouse is a GraphQL framework for Laravel that enables developers to serve GraphQL APIs by integrating with the Laravel ecosystem. It uses directives such as @all, @find, @create, and @delete to map GraphQL queries and mutations to Eloquent models, and provides @middleware for running Laravel middleware on specific fields or object types.

Tokens
171.7K
Snippets
650
Records
921
Agent score
84%

What's inside Lighthouse

  1. Overview of Lighthouse Lifecycle Events

    master

    Lighthouse dispatches a series of events within the Nuwave\\Lighthouse\\Events namespace during a request lifecycle. These events allow developers to hook into various stages of the GraphQL request, from the initial HTTP request to the final response construction.

    Lifecycle Order:

    1. StartRequest
    2. StartOperationOrOperations
    3. BuildSchemaString
    4. RegisterDirectiveNamespaces
    5. ManipulateAST
    6. StartExecution
    7. BuildExtensionsResponse
    8. ManipulateResult
    9. EndExecution
    10. EndOperationOrOperations
    11. EndRequest
  2. Overview of Lighthouse for Laravel

    master
    Lighthouse is a framework for serving GraphQL from Laravel. It allows you to build a GraphQL server on top of an existing Laravel application by leveraging the GraphQL Schema Definition Language (SDL) and maximizing code reuse with Laravel concepts. It is optimized for Eloquent, creating optimized database queries out of the box.
  3. Evaluation Order of Argument Directives

    master

    Directives implementing ArgDirective are processed in three distinct phases:

    1. Sanitize: Cleans input (e.g., trimming whitespace). Implemented via ArgSanitizerDirective.
    2. Validate: Ensures input conforms to expectations (e.g., email validation).
    3. Transform: Changes input before further processing (e.g., hashing passwords). Implemented via ArgTransformerDirective.

    Example execution order for @trim @rules @hash:

    1. Trim whitespace
    2. Run validation
    3. Hash the value
    type Mutation {
      createUser(
        password: String @trim @rules(apply: ["min:10,max:20"]) @hash
      ): User
    }
  4. Explore Lighthouse Plugins

    master

    Lighthouse can be extended with various community plugins to add functionality such as authentication, broadcasting, and settings management.

    Key plugins include:

    • joselfonseca/lighthouse-graphql-passport-auth: Passport authentication support.
    • daniel-de-wit/lighthouse-sanctum: Sanctum authentication support.
    • thekonz/lighthouse-redis-broadcaster: Redis-based broadcasting.
    • brightalley/lighthouse-apollo: Apollo integration.
    • roboroads/lighthouse-settings: Settings management.
    • lastdragon-ru/lara-asp-graphql: Strictly typed Searching and Sorting.
  5. Understand GraphQL Directives in Lighthouse

    master

    Directives are a primary way to add functionality to your GraphQL schema. They always begin with an @ symbol followed by a unique name and can be applied to specific parts of the schema (such as field definitions or arguments) depending on their defined location.

    Lighthouse provides many built-in directives for common tasks like filtering, authentication, and pagination.

  6. Understand the Lighthouse Request Lifecycle

    master

    Lighthouse follows a specific sequence to process incoming GraphQL requests. Understanding this lifecycle helps in debugging execution flow and identifying where custom logic (like middleware or resolvers) is applied.

    1. Routing: All requests to the GraphQL endpoint (typically /graphql) are handled by the GraphQLController.
    2. HTTP Middleware: Standard Laravel middleware is applied to the incoming HTTP request.
    3. Request Parsing: The request is parsed into GraphQL elements following the GraphQL specification.
    4. Schema Construction: Lighthouse collects types from .graphql files and programmatic definitions, applies transformations (like @paginate or @orderBy), and builds an executable schema. This step is usually cached for performance.
    5. Query Validation: The query is validated against the schema to ensure fields exist and variables are correct.
    6. Field Execution: Fields are executed from the root level down. Each field can be wrapped in field middleware (for auth, validation, etc.) before the resolver is called. This process repeats recursively for subselections.
    7. Error Handling: If a field fails, the subtree traversal stops, but Lighthouse collects the error and attempts to execute the rest of the query.
    8. Result Assembly: Results are formatted to match the query structure, errors are included, and the response is sent.
  7. Implement the Viewer pattern for scoped access

    master

    To limit users to only accessing data that belongs to them (e.g., a user seeing only their own notes), use the 'Viewer pattern'.

    1. Define a field (like me or viewer) on your Query type that represents the authenticated user using the @auth directive.
    2. Add related entities as relationships on the User type.

    This naturally restricts queries to the authenticated user's scope through the GraphQL nesting structure.

    type Query {
      me: User! @auth
    }
    
    type User {
      name: String!
      notes: [Note!]!
    }
    
    type Note {
      title: String!
      content: String!
    }
  8. Generate IDE helper for GraphQL SDL

    master

    To improve your IDE editing experience with SDL and schema directives, you can generate a definition file using the lighthouse:ide-helper command.

    This command requires the haydenpierce/class-finder package to be installed as a dev dependency:

    composer require --dev haydenpierce/class-finder
    php artisan lighthouse:ide-helper
  9. Upload files via multipart/form-data

    master

    File uploads must be sent using a multipart/form-data request following the graphql-multipart-request-spec.

    Note: If you are using the EnsureXHR middleware for CSRF protection, you must include the header X-Requested-With: XMLHttpRequest in your request.

    echo "test content" > my_file.txt
    
    curl localhost/graphql \
      -F operations='{ "query": "mutation ($file: Upload!) { upload(file: $file) }", "variables": { "file": null } }' \
      -F map='{ "0": ["variables.file"] }' \
      -F 0=@my_file.txt
  10. Use native PHP types for Enums and Custom Scalars

    master

    While Lighthouse is primarily SDL-first, you can use native webonyx/graphql-php type definitions. Note that native PHP types lack many Lighthouse-specific server-side directives and are more verbose.

    It is recommended to use native PHP types only for:

    • Enum types: To reuse existing constants in your code.
    • Custom Scalar types: Which must be implemented in PHP regardless.