GraphQL in PHP: webonyx/graphql-php and Lighthouse Libraries for API Creation

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

GraphQL PHP Library: webonyx/graphql-php and Lighthouse



GraphQL is a query language for APIs that allows clients to request only the necessary data. In the PHP ecosystem, the main library for implementing GraphQL is webonyx/graphql-php. It provides a complete set of tools for creating schemas, types, and resolvers. For the Laravel framework, there is the Lighthouse package, which extends the capabilities of graphql-php and simplifies development.



Installing webonyx/graphql-php

Installation is done via Composer:

composer require webonyx/graphql-php


Creating a Schema and Types

The foundation of GraphQL is a schema that defines data types and their relationships. Let's look at an example of creating a simple schema for retrieving a list of users.



<?phpuse GraphQL\\Type\\Definition\\ObjectType;use GraphQL\\Type\\Definition\\Type;use GraphQL\\Type\\Schema;use GraphQL\\GraphQL;

// Define the User type$userType = new ObjectType([ 'name' => 'User', 'fields' => [ 'id' => Type::int(), 'name' => Type::string(), 'email' => Type::string(), ]]);

// Define the Query type (root type for queries)$queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'user' => [ 'type' => $userType, 'args' => [ 'id' => Type::nonNull(Type::int()) ], 'resolve' => function ($root, $args) { // Example data - in a real project this would be a database query $users = [ 1 => ['id' => 1, 'name' => 'Ivan', 'email' => 'ivan@example.com'], 2 => ['id' => 2, 'name' => 'Maria', 'email' => 'maria@example.com'], ]; return $users[$args['id']] ?? null; } ], 'users' => [ 'type' => Type::listOf($userType), 'resolve' => function () { return [ ['id' => 1, 'name' => 'Ivan', 'email' => 'ivan@example.com'], ['id' => 2, 'name' => 'Maria', 'email' => 'maria@example.com'], ]; } ] ]]);

// Create the schema$schema = new Schema([ 'query' => $queryType]);

// Execute the query$rawInput = file_get_contents('php://input');$input = json_decode($rawInput, true);$query = $input['query'];$result = GraphQL::executeQuery($schema, $query);$output = $result->toArray();

header('Content-Type: application/json');echo json_encode($output);


Working with Mutations

In addition to queries (Query), GraphQL supports mutations (Mutation) for modifying data. An example of creating a mutation for adding a user:



<?php// Define the mutation type$mutationType = new ObjectType([    'name' => 'Mutation',    'fields' => [        'addUser' => [            'type' => $userType,            'args' => [                'name' => Type::nonNull(Type::string()),                'email' => Type::nonNull(Type::string())            ],            'resolve' => function ($root, $args) {                // Here should be code for saving to the database                return [                    'id' => 3,                    'name' => $args['name'],                    'email' => $args['email']                ];            }        ]    ]]);

// Update the schema$schema = new Schema([ 'query' => $queryType, 'mutation' => $mutationType]);


Using Lighthouse for Laravel

If you are working with Laravel, it is recommended to use Lighthouse. It automates schema creation based on Eloquent models and provides

Recommendations