PHPackages                             ufree/laravel-graphql - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. ufree/laravel-graphql

ActiveProject[Framework](/categories/framework)

ufree/laravel-graphql
=====================

Facebook GraphQL for Laravel

3.0.1(7y ago)027MITPHPPHP &gt;=7.0

Since Aug 13Pushed 7y ago1 watchersCompare

[ Source](https://github.com/xiebinbin/laravel-graphql)[ Packagist](https://packagist.org/packages/ufree/laravel-graphql)[ RSS](/packages/ufree-laravel-graphql/feed)WikiDiscussions develop Synced 2mo ago

READMEChangelog (1)Dependencies (7)Versions (74)Used By (0)

Differences from official package
=================================

[](#differences-from-official-package)

This version has been optimized for performance, and I keep up with the latest version of the [webonyx](https://github.com/webonyx/graphql-php) library. This version uses a `TypeRegistry` class inside the schema registration method to lazy load types as they are needed. This has increased performance in application with 500+ types registered by over 50%. I also stopped the unused `TypeAdded` event from firing, which also increased performance significantly.

The usage of the `TypeRegistry` complicates the library to a degree - you must now publish the path to your custom scalars directory and namespace in the `graphql.php` configuration file. When creating custom scalars, your `type` function must be configured as follows:

```
static public function type() {
        if(is_null(self::$_instance))
        {
            self::$_instance = new self();
        }
        return GraphQL::type(self::$_instance->name);
    }

```

It's important that anywhere you reference a GraphQL, you always call it with `GraphQL::type` rather than instantiating the class, as this will hook into the `TypeRegistry` class. If you don't do this, you'll get schema errors.

Laravel GraphQL
===============

[](#laravel-graphql)

Use Facebook GraphQL with Laravel 5 or Lumen. It is based on the PHP implementation [here](https://github.com/webonyx/graphql-php). You can find more information about GraphQL in the [GraphQL Introduction](http://facebook.github.io/react/blog/2015/05/01/graphql-introduction.html) on the [React](http://facebook.github.io/react) blog or you can read the [GraphQL specifications](https://facebook.github.io/graphql/). This is a work in progress.

This package is compatible with Eloquent model (or any other data source). See the example below.

[![Latest Stable Version](https://camo.githubusercontent.com/b0a334b5e74559b1232ca0b3a6f0e4264ef873f5efcdaa1b7ab4641de25ef88b/68747470733a2f2f706f7365722e707567782e6f72672f666f6c6b6c6f72652f6772617068716c2f762f737461626c652e737667)](https://packagist.org/packages/folklore/graphql)[![Build Status](https://camo.githubusercontent.com/d1b0a81889dc03c6f09e370a64f94ccbc3bfa8f9c83910a1e6d2e4f3f5b6684e/68747470733a2f2f7472617669732d63692e6f72672f466f6c6b6c6f72656174656c6965722f6c61726176656c2d6772617068716c2e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/Folkloreatelier/laravel-graphql)[![Total Downloads](https://camo.githubusercontent.com/82b200eb40b542519579144e03c08eff7930229153bf915839f5aa6d8b43a972/68747470733a2f2f706f7365722e707567782e6f72672f666f6c6b6c6f72652f6772617068716c2f646f776e6c6f6164732e737667)](https://packagist.org/packages/folklore/graphql)

---

### To use laravel-graphql with Relay, check the [feature/relay](https://github.com/Folkloreatelier/laravel-graphql/tree/feature/relay) branch.

[](#to-use-laravel-graphql-with-relay-check-the-featurerelay-branch)

---

Installation
------------

[](#installation)

Version 1.0 is released. If you are upgrading from older version, you can check [Upgrade to 1.0](docs/upgrade.md).

#### Dependencies:

[](#dependencies)

- [Laravel 5.x](https://github.com/laravel/laravel) or [Lumen](https://github.com/laravel/lumen)
- [GraphQL PHP](https://github.com/webonyx/graphql-php)

**1-** Require the package via Composer in your `composer.json`.

```
{
  "require": {
    "sonarsoftware/graphql": "~2.0.0"
  }
}
```

**2-** Run Composer to install or update the new requirement.

```
$ composer install
```

or

```
$ composer update
```

### Laravel &gt;= 5.5.x

[](#laravel--55x)

**1-** Publish the configuration file

```
$ php artisan vendor:publish --provider="Folklore\GraphQL\ServiceProvider"
```

**2-** Review the configuration file

```
config/graphql.php

```

Usage
-----

[](#usage)

- [Schemas](#schemas)
- [Creating a query](#creating-a-query)
- [Creating a mutation](#creating-a-mutation)
- [Adding validation to mutation](#adding-validation-to-mutation)

#### Advanced Usage

[](#advanced-usage)

- [Query variables](docs/advanced.md#query-variables)
- [Query nested resource](docs/advanced.md#query-nested-resource)
- [Enums](docs/advanced.md#enums)
- [Interfaces](docs/advanced.md#interfaces)
- [Custom field](docs/advanced.md#custom-field)
- [Eager loading relationships](docs/advanced.md#eager-loading-relationships)

### Schemas

[](#schemas)

Starting from version 1.0, you can define multiple schemas. Having multiple schemas can be useful if, for example, you want an endpoint that is public and another one that needs authentication.

You can define multiple schemas in the config:

```
'schema' => 'default',

'schemas' => [
    'default' => [
        'query' => [
            //'users' => 'App\GraphQL\Query\UsersQuery'
        ],
        'mutation' => [
            //'updateUserEmail' => 'App\GraphQL\Query\UpdateUserEmailMutation'
        ]
    ],
    'secret' => [
        'query' => [
            //'users' => 'App\GraphQL\Query\UsersQuery'
        ],
        'mutation' => [
            //'updateUserEmail' => 'App\GraphQL\Query\UpdateUserEmailMutation'
        ]
    ]
]
```

Or you can add schema using the facade:

```
GraphQL::addSchema('secret', [
    'query' => [
        'users' => 'App\GraphQL\Query\UsersQuery'
    ],
    'mutation' => [
        'updateUserEmail' => 'App\GraphQL\Query\UpdateUserEmailMutation'
    ]
]);
```

Afterwards, you can build the schema using the facade:

```
// Will return the default schema defined by 'schema' in the config
$schema = GraphQL::schema();

// Will return the 'secret' schema
$schema = GraphQL::schema('secret');

// Will build a new schema
$schema = GraphQL::schema([
    'query' => [
        //'users' => 'App\GraphQL\Query\UsersQuery'
    ],
    'mutation' => [
        //'updateUserEmail' => 'App\GraphQL\Query\UpdateUserEmailMutation'
    ]
]);
```

Or you can request the endpoint for a specific schema

```
// Default schema
http://homestead.app/graphql?query=query+FetchUsers{users{id,email}}

// Secret schema
http://homestead.app/graphql/secret?query=query+FetchUsers{users{id,email}}

```

### Creating a query

[](#creating-a-query)

First you need to create a type.

```
namespace App\GraphQL\Type;

use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Type as GraphQLType;

class UserType extends GraphQLType
{
    protected $attributes = [
        'name' => 'User',
        'description' => 'A user'
    ];

    /*
    * Uncomment following line to make the type input object.
    * http://graphql.org/learn/schema/#input-types
    */
    // protected $inputObject = true;

    public function fields()
    {
        return [
            'id' => [
                'type' => Type::nonNull(Type::string()),
                'description' => 'The id of the user'
            ],
            'email' => [
                'type' => Type::string(),
                'description' => 'The email of user'
            ]
        ];
    }

    // If you want to resolve the field yourself, you can declare a method
    // with the following format resolve[FIELD_NAME]Field()
    protected function resolveEmailField($root, $args)
    {
        return strtolower($root->email);
    }
}
```

Add the type to the `config/graphql.php` configuration file

```
'types' => [
    'User' => 'App\GraphQL\Type\UserType'
]
```

You could also add the type with the `GraphQL` Facade, in a service provider for example.

```
GraphQL::addType('App\GraphQL\Type\UserType', 'User');
```

Then you need to define a query that returns this type (or a list). You can also specify arguments that you can use in the resolve method.

```
namespace App\GraphQL\Query;

use GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Query;
use App\User;

class UsersQuery extends Query
{
    protected $attributes = [
        'name' => 'users'
    ];

    public function type()
    {
        return Type::listOf(GraphQL::type('User'));
    }

    public function args()
    {
        return [
            'id' => [
                'name' => 'id',
                'type' => Type::string()
            ],
            'email' => [
                'name' => 'email',
                'type' => Type::string()
            ]
        ];
    }

    public function resolve($root, $args)
    {
        if (isset($args['id'])) {
            return User::where('id' , $args['id'])->get();
        } else if(isset($args['email'])) {
            return User::where('email', $args['email'])->get();
        } else {
            return User::all();
        }
    }
}
```

If any part of the query has a default value, you can define this in the `args()` function by including `defaultValue` as an array key in one of the arguments, and setting the value to the default value. For example, if you had an optional argument in your query to `include_deleted_users` and the default value should be `false`, then you could edit the `args()` function as shown below:

```
public function args()
{
    return [
        'id' => [
            'name' => 'id',
            'type' => Type::string()
        ],
        'email' => [
            'name' => 'email',
            'type' => Type::string()
        ],
        'include_deleted_users' => [
            'name' => 'include_deleted_users',
            'type' => Type::boolean(),
            'defaultValue' => false
        ]
    ];
}

```

You can also include descriptions for query fields by adding a `description` array key - this will be shown in the schema, and picked up by tools like GraphiQL.

Add the query to the `config/graphql.php` configuration file

```
'schemas' => [
    'default' => [
        'query' => [
            'users' => 'App\GraphQL\Query\UsersQuery'
        ],
        // ...
    ]
]
```

And that's it. You should be able to query GraphQL with a request to the url `/graphql` (or anything you choose in your config). Try a GET request with the following `query` input

```
query FetchUsers {
  users {
    id
    email
  }
}

```

For example, if you use homestead:

```
http://homestead.app/graphql?query=query+FetchUsers{users{id,email}}

```

### Creating a mutation

[](#creating-a-mutation)

A mutation is like any other query, it accepts arguments (which will be used to do the mutation) and return an object of a certain type.

For example a mutation to update the password of a user. First you need to define the Mutation.

```
namespace App\GraphQL\Mutation;

use GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Mutation;
use App\User;

class UpdateUserPasswordMutation extends Mutation
{
    protected $attributes = [
        'name' => 'updateUserPassword'
    ];

    public function type()
    {
        return GraphQL::type('User');
    }

    public function args()
    {
        return [
            'id' => ['name' => 'id', 'type' => Type::nonNull(Type::string())],
            'password' => ['name' => 'password', 'type' => Type::nonNull(Type::string())]
        ];
    }

    public function resolve($root, $args)
    {
        $user = User::find($args['id']);

        if (!$user) {
            return null;
        }

        $user->password = bcrypt($args['password']);
        $user->save();

        return $user;
    }
}
```

As you can see in the `resolve` method, you use the arguments to update your model and return it.

You then add the mutation to the `config/graphql.php` configuration file

```
'schema' => [
    'default' => [
        'mutation' => [
            'updateUserPassword' => 'App\GraphQL\Mutation\UpdateUserPasswordMutation'
        ],
        // ...
    ]
]
```

You should then be able to use the following query on your endpoint to do the mutation.

```
mutation users {
  updateUserPassword(id: "1", password: "newpassword") {
    id
    email
  }
}

```

if you use homestead:

```
http://homestead.app/graphql?query=mutation+users{updateUserPassword(id: "1", password: "newpassword"){id,email}}

```

#### Adding validation to mutation

[](#adding-validation-to-mutation)

It is possible to add validation rules to mutation. It uses the laravel `Validator` to performs validation against the `args`.

When creating a mutation, you can add a method to define the validation rules that apply by doing the following:

```
namespace App\GraphQL\Mutation;

use GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Mutation;
use App\User;

class UpdateUserEmailMutation extends Mutation
{
    protected $attributes = [
        'name' => 'UpdateUserEmail'
    ];

    public function type()
    {
        return GraphQL::type('User');
    }

    public function args()
    {
        return [
            'id' => ['name' => 'id', 'type' => Type::string()],
            'email' => ['name' => 'email', 'type' => Type::string()]
        ];
    }

    public function rules()
    {
        return [
            'id' => ['required'],
            'email' => ['required', 'email']
        ];
    }

    public function resolve($root, $args)
    {
        $user = User::find($args['id']);

        if (!$user) {
            return null;
        }

        $user->email = $args['email'];
        $user->save();

        return $user;
    }
}
```

Alternatively you can define rules with each args

```
class UpdateUserEmailMutation extends Mutation
{
    //...

    public function args()
    {
        return [
            'id' => [
                'name' => 'id',
                'type' => Type::string(),
                'rules' => ['required']
            ],
            'email' => [
                'name' => 'email',
                'type' => Type::string(),
                'rules' => ['required', 'email']
            ]
        ];
    }

    //...
}
```

When you execute a mutation, it will returns the validation errors. Since GraphQL specifications define a certain format for errors, the validation errors messages are added to the error object as a extra `validation` attribute. To find the validation error, you should check for the error with a `message` equals to `'validation'`, then the `validation` attribute will contain the normal errors messages returned by the Laravel Validator.

```
{
  "data": {
    "updateUserEmail": null
  },
  "errors": [
    {
      "message": "validation",
      "locations": [
        {
          "line": 1,
          "column": 20
        }
      ],
      "validation": {
        "email": [
          "The email is invalid."
        ]
      }
    }
  ]
}
```

###  Health Score

32

—

LowBetter than 71% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community20

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 71.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~18 days

Recently: every ~43 days

Total

71

Last Release

2624d ago

Major Versions

v0.4.9 → v1.0.02016-10-17

1.0.39 → 2.0.02018-09-10

2.0.5 → 3.0.12019-03-03

PHP version history (2 changes)v0.1.1PHP &gt;=5.5.9

2.0.0PHP &gt;=7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/959a85a777fb942cc82e014170fe9f0ad67ec454129a0b594b2d024d0dcf3258?d=identicon)[soda](/maintainers/soda)

---

Top Contributors

[![dmongeau](https://avatars.githubusercontent.com/u/124966?v=4)](https://github.com/dmongeau "dmongeau (245 commits)")[![SonarSoftware](https://avatars.githubusercontent.com/u/12124408?v=4)](https://github.com/SonarSoftware "SonarSoftware (27 commits)")[![n1ru4l](https://avatars.githubusercontent.com/u/14338007?v=4)](https://github.com/n1ru4l "n1ru4l (8 commits)")[![kevinvdburgt](https://avatars.githubusercontent.com/u/1987802?v=4)](https://github.com/kevinvdburgt "kevinvdburgt (8 commits)")[![inxilpro](https://avatars.githubusercontent.com/u/21592?v=4)](https://github.com/inxilpro "inxilpro (7 commits)")[![ktogo](https://avatars.githubusercontent.com/u/11808367?v=4)](https://github.com/ktogo "ktogo (6 commits)")[![c3riz88](https://avatars.githubusercontent.com/u/13783395?v=4)](https://github.com/c3riz88 "c3riz88 (5 commits)")[![petecoop](https://avatars.githubusercontent.com/u/1655361?v=4)](https://github.com/petecoop "petecoop (3 commits)")[![dimitri-koenig](https://avatars.githubusercontent.com/u/4375825?v=4)](https://github.com/dimitri-koenig "dimitri-koenig (3 commits)")[![gotrecillo](https://avatars.githubusercontent.com/u/9203112?v=4)](https://github.com/gotrecillo "gotrecillo (3 commits)")[![Roemerb](https://avatars.githubusercontent.com/u/4710404?v=4)](https://github.com/Roemerb "Roemerb (3 commits)")[![rafaelrenanpacheco](https://avatars.githubusercontent.com/u/12160864?v=4)](https://github.com/rafaelrenanpacheco "rafaelrenanpacheco (2 commits)")[![rafaelfess](https://avatars.githubusercontent.com/u/8284165?v=4)](https://github.com/rafaelfess "rafaelfess (2 commits)")[![spamoom](https://avatars.githubusercontent.com/u/99203?v=4)](https://github.com/spamoom "spamoom (2 commits)")[![trihatmaja](https://avatars.githubusercontent.com/u/6902421?v=4)](https://github.com/trihatmaja "trihatmaja (2 commits)")[![adamroyle](https://avatars.githubusercontent.com/u/25002779?v=4)](https://github.com/adamroyle "adamroyle (2 commits)")[![pelletiermaxime](https://avatars.githubusercontent.com/u/1801684?v=4)](https://github.com/pelletiermaxime "pelletiermaxime (2 commits)")[![alnutile](https://avatars.githubusercontent.com/u/365385?v=4)](https://github.com/alnutile "alnutile (2 commits)")[![withinboredom](https://avatars.githubusercontent.com/u/1883296?v=4)](https://github.com/withinboredom "withinboredom (1 commits)")[![cppcho](https://avatars.githubusercontent.com/u/1287355?v=4)](https://github.com/cppcho "cppcho (1 commits)")

---

Tags

frameworklaravelgraphqlreact

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ufree-laravel-graphql/health.svg)

```
[![Health](https://phpackages.com/badges/ufree-laravel-graphql/health.svg)](https://phpackages.com/packages/ufree-laravel-graphql)
```

###  Alternatives

[rebing/graphql-laravel

Laravel wrapper for PHP GraphQL

2.2k7.1M26](/packages/rebing-graphql-laravel)[graham-campbell/markdown

Markdown Is A CommonMark Wrapper For Laravel

1.3k7.1M63](/packages/graham-campbell-markdown)[lanin/laravel-api-exceptions

All in one solution for exception for JSON REST APIs on Laravel and Lumen.

40102.4k](/packages/lanin-laravel-api-exceptions)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
