Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Lighthouse
https://github.com/nuwave/lighthouse
Admin
Lighthouse is a GraphQL framework that integrates with Laravel applications, combining the best of
...
Tokens:
519,369
Snippets:
2,084
Trust Score:
7.3
Update:
8 months ago
Context
Skills
Chat
Benchmark
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Lighthouse GraphQL Framework Lighthouse is a GraphQL framework for Laravel that simplifies building GraphQL APIs by combining declarative schema-first design with powerful directives. It seamlessly integrates with Eloquent ORM, providing automatic query generation, relationship loading, and mutation handling through schema annotations. The framework eliminates boilerplate code by using schema directives to define data fetching, authorization, validation, and caching behavior directly in GraphQL schema files. Lighthouse follows the code-first approach where you define your GraphQL schema using SDL (Schema Definition Language) and use directives to map schema fields to Laravel application logic. It supports advanced features including relay-style cursor pagination, DataLoader-based batch loading for N+1 query prevention, real-time subscriptions via WebSockets, input validation, field-level authorization, query caching, and Apollo Federation. The framework is production-ready with built-in security features like query complexity analysis, depth limiting, and automatic persisted queries. ## Installation and Configuration ### Installing Lighthouse via Composer ```bash # Install Lighthouse package composer require nuwave/lighthouse # Publish configuration file php artisan vendor:publish --tag=lighthouse-config # Publish default GraphQL schema php artisan vendor:publish --tag=lighthouse-schema ``` ### Basic Configuration ```php // config/lighthouse.php return [ 'route' => [ 'uri' => '/graphql', 'name' => 'graphql', 'middleware' => [ \Nuwave\Lighthouse\Http\Middleware\AcceptJson::class, \Nuwave\Lighthouse\Http\Middleware\AttemptAuthentication::class, ], ], 'schema_path' => base_path('graphql/schema.graphql'), 'namespaces' => [ 'models' => ['App', 'App\\Models'], 'queries' => 'App\\GraphQL\\Queries', 'mutations' => 'App\\GraphQL\\Mutations', ], 'pagination' => [ 'default_count' => null, 'max_count' => null, ], 'query_cache' => [ 'enable' => true, 'mode' => 'store', // 'store', 'opcache', or 'hybrid' 'ttl' => 86400, ], ]; ``` ## HTTP Endpoint ### Making GraphQL Requests ```bash # Query request curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -H "Accept: application/json" \ -d '{ "query": "{ user(id: 1) { id name email } }" }' # Response { "data": { "user": { "id": "1", "name": "John Doe", "email": "john@example.com" } } } # Query with variables curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "query GetUser($id: ID!) { user(id: $id) { id name email } }", "variables": { "id": "1" } }' # Mutation request curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "mutation { createUser(name: \"Jane\", email: \"jane@example.com\") { id name } }" }' ``` ## Query Directives ### @all - Fetch All Models ```graphql type Query { users: [User!]! @all posts(status: String): [Post!]! @all(scopes: ["published"]) } type User { id: ID! name: String! email: String! } ``` ```bash # Fetch all users curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "{ users { id name email } }" }' ``` ### @find - Find Single Model ```graphql type Query { user( id: ID @eq @rules(apply: ["prohibits:email", "required_without:email"]) email: String @eq @rules(apply: ["prohibits:id", "required_without:id", "email"]) ): User @find } ``` ```bash # Find by ID curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "{ user(id: 1) { id name email } }" }' # Find by email curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "{ user(email: \"john@example.com\") { id name } }" }' ``` ### @paginate - Paginated Query ```graphql type Query { users( name: String @where(operator: "like") orderBy: [OrderByClause!] @orderBy ): UserPaginator @paginate(defaultCount: 10) } ``` ```bash # Paginated request curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "{ users(first: 10, page: 1) { data { id name email } paginatorInfo { currentPage lastPage total } } }" }' # Response { "data": { "users": { "data": [ { "id": "1", "name": "John", "email": "john@example.com" } ], "paginatorInfo": { "currentPage": 1, "lastPage": 5, "total": 50 } } } } ``` ### @where - Filter Queries ```graphql type Query { users( name: String @where(operator: "like") email: String @where(operator: "=") created_after: DateTime @where(key: "created_at", operator: ">=") ): [User!]! @all } ``` ```bash # Filter by name (LIKE operator) curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "{ users(name: \"%john%\") { id name email } }" }' ``` ## Mutation Directives ### @create - Create Model ```graphql type Mutation { createUser( name: String! @rules(apply: ["required", "min:3"]) email: String! @rules(apply: ["required", "email", "unique:users,email"]) password: String! @rules(apply: ["required", "min:8"]) @hash ): User @create } ``` ```bash curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "mutation { createUser(name: \"Jane Doe\", email: \"jane@example.com\", password: \"secret123\") { id name email } }" }' ``` ### @update - Update Model ```graphql type Mutation { updateUser( id: ID! @eq name: String @rules(apply: ["min:3"]) email: String @rules(apply: ["email"]) ): User @update } ``` ```bash curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "mutation { updateUser(id: 1, name: \"John Smith\") { id name email } }" }' ``` ### @upsert - Create or Update ```graphql type Mutation { upsertUser( id: ID name: String! email: String! ): User @upsert } ``` ```bash curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "mutation { upsertUser(email: \"user@example.com\", name: \"New User\") { id name email } }" }' ``` ### @delete - Delete Model ```graphql type Mutation { deleteUser(id: ID! @eq): User @delete } ``` ```bash curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "mutation { deleteUser(id: 5) { id name } }" }' ``` ## Relationship Directives ### @belongsTo - Load Parent Relationship ```graphql type Post { id: ID! title: String! author: User @belongsTo } type User { id: ID! name: String! } ``` ```bash curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "{ posts { id title author { id name } } }" }' ``` ### @hasMany - Load Children Relationships ```graphql type User { id: ID! name: String! posts: [Post!]! @hasMany publishedPosts: [Post!]! @hasMany(relation: "posts", scopes: ["published"]) } ``` ```bash curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "{ user(id: 1) { id name posts { id title } publishedPosts { id title } } }" }' ``` ### @belongsToMany - Many-to-Many Relationships ```graphql type User { id: ID! name: String! roles: [Role!]! @belongsToMany } type Role { id: ID! name: String! users: [User!]! @belongsToMany } ``` ```bash curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "{ user(id: 1) { id name roles { id name } } }" }' ``` ## Authorization and Validation ### @can - Authorization Directive ```graphql type Mutation { updatePost(id: ID!, title: String!): Post @can(ability: "update", find: "id") @update } type Query { adminUsers: [User!]! @can(ability: "viewAny", model: "App\\Models\\User") @all } ``` ```php // app/Policies/PostPolicy.php class PostPolicy { public function update(User $user, Post $post): bool { return $user->id === $post->author_id; } } ``` ```bash curl -X POST http://localhost/graphql \ -H "Authorization: Bearer TOKEN" \ -H "Content-Type: application/json" \ -d '{ "query": "mutation { updatePost(id: 1, title: \"New Title\") { id title } }" }' ``` ### @rules - Validation Directive ```graphql type Mutation { createPost( title: String! @rules(apply: ["required", "min:5", "max:255"]) content: String! @rules(apply: ["required", "min:20"]) category_id: ID! @rules(apply: ["required", "exists:categories,id"]) ): Post @create } ``` ```bash # Valid request curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "mutation { createPost(title: \"Valid Title\", content: \"This is long enough content\", category_id: 1) { id } }" }' # Invalid request - validation error curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "mutation { createPost(title: \"Hi\", content: \"Short\", category_id: 999) { id } }" }' # Response { "errors": [{ "message": "validation", "extensions": { "validation": { "title": ["The title must be at least 5 characters."], "content": ["The content must be at least 20 characters."] } } }] } ``` ### @guard - Authentication Guard ```graphql type Query { me: User @auth adminData: AdminData @guard(with: ["admin"]) } ``` ```bash curl -X POST http://localhost/graphql \ -H "Authorization: Bearer JWT_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "query": "{ me { id name email } }" }' ``` ## Custom Field Resolvers ### @field - Custom Resolver Function ```graphql type Query { stats: Stats @field(resolver: "App\\GraphQL\\Queries\\StatsResolver") } type User { fullName: String @field(resolver: "fullName") } ``` ```php // app/GraphQL/Queries/StatsResolver.php namespace App\GraphQL\Queries; class StatsResolver { public function __invoke($rootValue, array $args) { return [ 'totalUsers' => User::count(), 'totalPosts' => Post::count(), ]; } } // app/Models/User.php class User extends Model { public function fullName(): string { return "{$this->first_name} {$this->last_name}"; } } ``` ```bash curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "{ stats { totalUsers totalPosts } }" }' ``` ### @method - Resolve via Model Method ```graphql type User { id: ID! firstName: String! lastName: String! fullName: String! @method(name: "getFullName") initials: String! @method } ``` ```php // app/Models/User.php class User extends Model { public function getFullName(): string { return "{$this->firstName} {$this->lastName}"; } public function initials(): string { return strtoupper($this->firstName[0] . $this->lastName[0]); } } ``` ```bash curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "{ user(id: 1) { fullName initials } }" }' ``` ## Caching ### @cache - Field-Level Caching ```graphql type Query { expensiveStats: Stats @cache(maxAge: 3600) userProfile(id: ID!): User @cache(maxAge: 300) @find } type User { id: ID! name: String! postsCount: Int! @cache(maxAge: 60) @count(relation: "posts") } ``` ```bash curl -X POST http://localhost/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "{ expensiveStats { totalUsers totalPosts } }" }' ``` ### Query Cache Configuration ```php // config/lighthouse.php 'query_cache' => [ 'enable' => true, 'mode' => 'opcache', // Faster performance with OPcache 'opcache_path' => base_path('bootstrap/cache'), 'ttl' => 86400, ], ``` ```bash # Clear query cache php artisan lighthouse:clear-query-cache # Clear schema cache php artisan lighthouse:clear-schema-cache ``` ## Testing with Lighthouse ### PHPUnit Testing Helper ```php // tests/Feature/GraphQL/UserTest.php namespace Tests\Feature\GraphQL; use Tests\TestCase; use Nuwave\Lighthouse\Testing\MakesGraphQLRequests; use Illuminate\Foundation\Testing\RefreshDatabase; class UserTest extends TestCase { use RefreshDatabase, MakesGraphQLRequests; public function test_can_fetch_user(): void { $user = User::factory()->create([ 'name' => 'John Doe', 'email' => 'john@example.com', ]); $response = $this->graphQL(' query GetUser($id: ID!) { user(id: $id) { id name email } } ', [ 'id' => $user->id, ]); $response->assertJson([ 'data' => [ 'user' => [ 'id' => (string) $user->id, 'name' => 'John Doe', 'email' => 'john@example.com', ], ], ]); } public function test_can_create_user(): void { $response = $this->graphQL(' mutation CreateUser($name: String!, $email: String!) { createUser(name: $name, email: $email) { id name email } } ', [ 'name' => 'Jane Doe', 'email' => 'jane@example.com', ]); $response->assertJsonStructure([ 'data' => [ 'createUser' => ['id', 'name', 'email'], ], ]); $this->assertDatabaseHas('users', [ 'name' => 'Jane Doe', 'email' => 'jane@example.com', ]); } public function test_validation_errors(): void { $response = $this->graphQL(' mutation { createUser(name: "", email: "invalid") { id } } '); $response->assertGraphQLValidationError('name', 'required') ->assertGraphQLValidationError('email', 'email'); } } ``` ## Programmatic Execution ### Executing GraphQL from PHP ```php use Nuwave\Lighthouse\GraphQL; use Nuwave\Lighthouse\Support\Contracts\CreatesContext; // Execute query string $graphQL = app(GraphQL::class); $contextFactory = app(CreatesContext::class); $context = $contextFactory->generate(request()); $result = $graphQL->executeQueryString( query: '{ user(id: 1) { id name email } }', context: $context, variables: [], root: null, operationName: null ); // Result: ['data' => ['user' => ['id' => '1', 'name' => '...', 'email' => '...']]] // Execute with variables $result = $graphQL->executeQueryString( query: 'query GetUser($id: ID!) { user(id: $id) { id name } }', context: $context, variables: ['id' => 5], ); // Execute parsed query for better performance use GraphQL\Language\Parser; $parsedQuery = Parser::parse('{ users { id name } }'); $result = $graphQL->executeParsedQuery( query: $parsedQuery, context: $context, variables: [], ); ``` ## Summary and Integration Lighthouse provides a comprehensive GraphQL implementation for Laravel with minimal code required. The main use cases include building APIs for mobile and web applications where you need flexible data fetching, implementing Backend-for-Frontend (BFF) patterns, creating admin panels with complex filtering and pagination, and developing real-time applications with subscriptions. Lighthouse's directive-based approach means most CRUD operations require only schema definitions without writing resolver code. Integration with existing Laravel applications is seamless - Lighthouse uses your existing Eloquent models, authentication guards, authorization policies, and validation rules. Performance is optimized through query caching (opcache mode recommended for production), automatic DataLoader batching to prevent N+1 queries, and support for persisted queries. The framework scales from simple APIs to complex federated GraphQL services, with built-in support for Apollo Federation, tracing, and monitoring. For production deployments, enable schema caching, configure query complexity limits, implement rate limiting with @throttle directive, and use the validation cache for frequently executed queries.