LARAVEL

Laravel GraphQL API Development

April 10, 2024 22 min read

Introduction

GraphQL provides a flexible alternative to REST APIs. Laravel Lighthouse makes implementing GraphQL APIs straightforward. This guide covers building GraphQL APIs with Laravel.

Installation

Setup Lighthouse

composer require nuwave/lighthouse

// Publish config
php artisan vendor:publish --provider="Nuwave\Lighthouse\LighthouseServiceProvider"

# GraphQL endpoint: /graphql

Configuration

// config/graphql.php
return [
    'route' => [
        'prefix' => 'graphql',
        'middleware' => ['web'],
    ],
    'schema' => [
        'register' => __DIR__.'/schema.graphql',
    ],
];

Schema Definition

Create Schema

# schema.graphql
type Query {
    users: [User!]! @all
    user(id: ID @eq): User @find
}

type User {
    id: ID!
    name: String!
    email: String!
    posts: [Post!]! @hasMany
}

type Post {
    id: ID!
    title: String!
    body: String!
    author: User! @belongsTo
}

Queries

Basic Queries

// Query users
query {
    users {
        id
        name
        email
    }
}

// Query with filter
query {
    user(id: 1) {
        name
        posts {
            title
        }
    }
}

Custom Resolvers

// Custom query
type Query {
    latestPosts(limit: Int = 10): [Post!]!
        @field(resolver: "App\\GraphQL\\Queries\\LatestPosts@resolve")
}

Mutations

Create Mutation

// Add mutation to schema
type Mutation {
    createUser(
        name: String! @rules(apply: ["required"])
        email: String! @rules(apply: ["required", "email", "unique:users"])
    ): User @create
}

Update Mutation

type Mutation {
    updateUser(
        id: ID!
        name: String
    ): User @update
}

Delete Mutation

type Mutation {
    deleteUser(id: ID!): User @delete
}

Relationships

HasMany

type User {
    posts: [Post!]! @hasMany
}

BelongsTo

type Post {
    author: User! @belongsTo
}

Many-to-Many

type User {
    roles: [Role!]! @belongsToMany
}

Pagination

Offset Pagination

type Query {
    users(first: Int, page: Int): [User!]! @paginate
}

Cursor Pagination

type Query {
    users(first: Int, after: String): UserConnection 
        @paginate(builder: "App\\GraphQL\\Queries\\Users@resolve")
}

Query with Pagination

query {
    users(first: 10, page: 1) {
        data {
            id
            name
        }
        paginatorInfo {
            currentPage
            lastPage
            total
        }
    }
}

Summary

Laravel Lighthouse provides powerful GraphQL capabilities. GraphQL offers flexible data fetching that can improve API performance and developer experience.

For more Laravel tutorials, check out Laravel API Authentication and Acumatica REST API.