Backend Development 1 min read 903 views

Building GraphQL APIs with Laravel: A Complete Guide

Learn how to build powerful GraphQL APIs with Laravel using Lighthouse PHP. From schema design to real-time subscriptions.

E
GraphQL API development

Introduction to GraphQL with Laravel

GraphQL provides a flexible alternative to REST APIs. With Laravel and Lighthouse PHP, you can build powerful, type-safe APIs.

Step 1: Install Lighthouse

composer require nuwave/lighthouse
php artisan vendor:publish --tag=lighthouse-schema

Step 2: Define Your Schema

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

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

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

Step 3: Mutations

type Mutation {
    createUser(input: CreateUserInput! @spread): User! @create
    updateUser(id: ID!, input: UpdateUserInput! @spread): User! @update
    deleteUser(id: ID!): User! @delete
}

input CreateUserInput {
    name: String!
    email: String!
    password: String! @hash
}

Step 4: Custom Resolvers

// app/GraphQL/Queries/UserQuery.php
class UserQuery
{
    public function active($root, array $args)
    {
        return User::where('is_active', true)->get();
    }
}

Step 5: Subscriptions

type Subscription {
    postCreated: Post!
}

// Broadcasting the event
event(new PostCreated($post));

GraphQL with Laravel provides a powerful, flexible API layer for modern applications.

Share this article:
ES

Written by Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!