Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

graphql-laravel

> 编程语言
Open source

Laravel wrapper for Facebook's GraphQL

2.2K stars0 likes2 views
WebsiteGitHub

About

Laravel wrapper for Facebook's GraphQL

Laravel GraphQL

This package provides a code-first integration of GraphQL for Laravel. It is based on the PHP port of GraphQL reference implementation. You define your schema entirely in PHP classes (types, queries, mutations) rather than in .graphql schema files. You can find more information about GraphQL in the Introduction to GraphQL or you can read the GraphQL specifications.

  • Allows creating queries and mutations as request endpoints
  • Supports multiple schemas
    • per schema queries/mutations/types
    • per schema HTTP middlewares
    • per schema GraphQL execution middlewares
  • Custom GraphQL resolver middleware can be defined for each query/mutation
  • Two data loading strategies for avoiding n+1 queries:
    • Dataloaders -- uses webonyx/graphql-php's built-in deferred resolution to batch field loads from any data source
    • SelectFields (optional separate package) -- analyzes the GraphQL query to generate optimized Eloquent select() and eager-loaded with() calls
  • Queries return types, which can have custom privacy settings

Note: GraphQL subscriptions are not supported by this package. If you need real-time push functionality, consider a dedicated solution like Lighthouse (which has subscription support) or implement subscriptions separately via Laravel broadcasting / WebSockets.

Table of Contents

  • Requirements
  • Installation
  • Quick Start
    • 1. Create a Type
    • 2. Create a Query
    • 3. Register in config
    • 4. Test it
    • What's next?
  • Concepts
    • A word on declaring a field nonNull
  • Data loading
    • Dataloaders (deferred resolution)
    • Choosing an approach
  • Middleware Overview
    • HTTP middleware
    • GraphQL execution middleware
    • GraphQL resolver middleware
  • Schemas
    • Route attributes
    • Schema classes
  • Creating a query
  • Creating a mutation
    • File uploads
      • Vue.js example
      • Vanilla JavaScript
  • Validation
    • Example defining rules in each argument
    • Example using the rules() method
    • Example using Laravel's validator directly
    • Handling validation errors
    • Customizing error messages
    • Customizing attributes
    • Cross-field validation rules in nested input types
    • Misc notes
  • Resolve method
  • Resolver middleware
    • Defining middleware
    • Registering middleware
    • Terminable middleware
  • Authorization
  • Privacy
  • Query variables
  • Custom field
    • Even better reusable fields
  • Dataloaders
    • Creating a loader
    • Using a loader in a type
    • Using a DataLoader library
  • Eager loading relationships
  • Type relationship query
  • Pagination
  • Batching
  • Scalar types
  • Enums
  • Unions
  • Interfaces
    • Supporting custom queries on interface relations
    • Sharing interface fields
  • Input Object
  • OneOf Input Objects
    • Creating a OneOf Input Type
    • Using OneOf Input Types
    • Generating OneOf Input Types
  • Type modifiers
  • Field and input alias
  • JSON columns
  • Field deprecation
  • Default field resolver
  • Macros
  • Automatic Persisted Queries support
    • Notes
    • Client example
  • Tracing / Observability
    • Enabling OpenTelemetry
    • Per-field resolver tracing
    • Custom tracing drivers
    • Per-schema tracing
  • Security
    • Introspection
    • Query depth limiting
    • Query complexity analysis
    • Batching limits
    • GET requests and read-only enforcement
    • Recommended production configuration
  • Error handling
    • Built-in error types
    • Error response format
    • Error reporting
    • Customizing error formatting
  • Misc features
    • Detecting unused variables
  • Configuration options
  • Performance considerations
    • Wrap Types
      • Using wrap types with SelectFields
  • Known limitations
    • SelectFields related
  • GraphQL testing clients
  • Testing
    • Querying an endpoint
    • Using query variables
    • Testing mutations
    • Testing a non-default schema
    • Asserting errors
  • Upgrading

Requirements

Dependency Version
PHP ^8.2
Laravel 12.x - 13.x
webonyx/graphql-php ^15.22.1

Optional dependencies:

Package Purpose
open-telemetry/api ^1.0 Required for the OpenTelemetry tracing driver
mll-lab/laravel-graphiql Interactive in-browser GraphiQL IDE

Installation

Require the package via Composer:

composer require rebing/graphql-laravel

Publish the configuration file via Laravel artisan:

php artisan vendor:publish --provider="Rebing\GraphQL\GraphQLServiceProvider"

Review the configuration file:

config/graphql.php

Quick Start

Get a working GraphQL endpoint in under 5 minutes -- no database required.

1. Create a Type

Use the artisan generator to scaffold a type:

php artisan make:graphql:type BookType

Edit the generated app/GraphQL/Types/BookType.php:

…

2. Create a Query

php artisan make:graphql:query BooksQuery

Edit app/GraphQL/Queries/BooksQuery.php:

…

3. Register in config

Add the type and query to the default schema in config/graphql.php:

'schemas' => [
    'default' => [
        'query' => [
            App\GraphQL\Queries\BooksQuery::class,
        ],
        'mutation' => [],
        'types' => [
            App\GraphQL\Types\BookType::class,
        ],
    ],
],

4. Test it

Start the dev server and send a query:

php artisan serve
curl -X POST -H "Content-Type: application/json" \
  -d '{"query": "{ books { id title author } }"}' \
  http://localhost:8000/graphql

Expected response:

{
    "data": {
        "books": [
            {"id": 1, "title": "The Great Gatsby", "author": "F. Scott Fitzgerald"},
            {"id": 2, "title": "1984", "author": "George Orwell"},
            {"id": 3, "title": "To Kill a Mockingbird", "author": "Harper Lee"}
        ]
    }
}

Try filtering with an argument:

curl -X POST -H "Content-Type: application/json" \
  -d '{"query": "{ books(title: \"1984\") { id title } }"}' \
  http://localhost:8000/graphql

Tip: For an interactive experience, install GraphiQL (composer require mll-lab/laravel-graphiql --dev) and visit /graphiql in your browser.

Note: Introspection is disabled by default. To enable it during development (required for GraphiQL and IDE tooling), set GRAPHQL_DISABLE_INTROSPECTION=false in your .env file.

What's next?

You now have a working GraphQL API. From here you can:

  • Optimize data loading -- see Dataloaders for the recommended way to avoid n+1 queries with any data source
  • Use Eloquent models -- see Creating a query for a full example with database-backed types; for Eloquent-specific column optimization see the optional rebing/graphql-laravel-select-fields package
  • Add mutations -- see Creating a mutation to modify data
  • Add validation -- see Validation for built-in Laravel validation rules on arguments
  • Add authorization -- see Authorization for per-operation access control
  • Explore all generators -- run php artisan list make:graphql to see all 12 available scaffolding commands

Concepts

Before diving head first into code, it's good to familiarize yourself with the concepts surrounding GraphQL. If you've already experience with GraphQL, feel free to skip this part.

  • "schema"
    A GraphQL schema defines all the queries, mutations and types associated with it.
  • "queries" and "mutations"
    The "methods" you call in your GraphQL request (think about your REST endpoint)
  • "types"
    Besides the primitive scalars like int and string, custom "shapes" can be defined and returned via custom types. They can map to your database models or basically any data you want to return.
  • "resolver"
    Any time data is returned, it is "resolved". Usually in query/mutations this specifies the primary way to retrieve your data. A common strategy is dataloaders (deferred batching). See Data loading for more details.

Typically, all queries/mutations/types are defined using the $attributes property and the args() / fields() methods as well as the resolve() method.

args/fields again return a configuration array for each field they supported. Those fields usually support these shapes

  • the "key" is the name of the field
  • type (required): a GraphQL specifier for the type supported here

Optional keys are:

  • description: made available when introspecting the GraphQL schema
  • resolve: override the default field resolver
  • deprecationReason: document why something is deprecated

A word on declaring a field nonNull

It's quite common, and actually good practice, to see the gracious use of Type::nonNull() on any kind of input and/or output fields.

The more specific the intent of your type system, the better for the consumer.

Some examples

  • if you require a certain field for a query/mutation argument, declare it non null
  • if you

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHP

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言