All Projects → folkloreinc → Laravel Graphql

folkloreinc / Laravel Graphql

Facebook GraphQL for Laravel 5. It supports Relay, eloquent models, validation and GraphiQL.

Programming Languages

PHP
23972 projects - #3 most used programming language
shell
77523 projects

Projects that are alternatives of or similar to Laravel Graphql

Lighthouse Utils
An add-on to Lighthouse to auto-generate CRUD actions from types https://github.com/nuwave/lighthouse
Stars: ✭ 26 (-98.55%)
Mutual labels:  graphql, relay, laravel
Relay Northwind App
A complex React, Relay, GraphQL demo app. Online demo:
Stars: ✭ 104 (-94.2%)
Mutual labels:  graphql, relay
React Transmit
Relay-inspired library based on Promises instead of GraphQL.
Stars: ✭ 1,335 (-25.54%)
Mutual labels:  graphql, relay
Graphql Live Query
Realtime GraphQL Live Queries with JavaScript
Stars: ✭ 112 (-93.75%)
Mutual labels:  graphql, relay
Requent
A GraphQL like interface to map a request to eloquent query with data transformation for Laravel.
Stars: ✭ 78 (-95.65%)
Mutual labels:  graphql, laravel
Tkframework
react + relay + redux + saga + graphql + webpack
Stars: ✭ 83 (-95.37%)
Mutual labels:  graphql, relay
Laqul
A complete starter kit that allows you create amazing apps that look native thanks to the Quasar Framework. Powered by an API developed in Laravel Framework using the easy GraphQL queries language. And ready to use the Google Firebase features.
Stars: ✭ 110 (-93.87%)
Mutual labels:  graphql, laravel
Graphql Query Test Mock
Easily mock GraphQL queries in your Relay Modern / Apollo / any-other-GraphQL-client tests.
Stars: ✭ 49 (-97.27%)
Mutual labels:  graphql, relay
Relay Example
[READONLY] 💝 Examples of common Relay patterns used in real-world applications. This repository is automatically exported from https://github.com/adeira/universe via Shipit
Stars: ✭ 126 (-92.97%)
Mutual labels:  graphql, relay
Graphql Sequelize Crud
Automatically generate queries and mutations from Sequelize models
Stars: ✭ 129 (-92.81%)
Mutual labels:  graphql, relay
Graphbrainz
A fully-featured GraphQL interface for the MusicBrainz API.
Stars: ✭ 130 (-92.75%)
Mutual labels:  graphql, relay
Rpg Boilerplate
Relay (React), Postgres, and Graphile (GraphQL): A Modern Frontend and API Boilerplate
Stars: ✭ 62 (-96.54%)
Mutual labels:  graphql, relay
Laravel Graphql
GraphQL implementation with power of Laravel
Stars: ✭ 56 (-96.88%)
Mutual labels:  graphql, laravel
Graphql Relay Js
A library to help construct a graphql-js server supporting react-relay.
Stars: ✭ 1,331 (-25.77%)
Mutual labels:  graphql, relay
Laravel Vuejs.com
Laravel and VueJs Blog, using Laravel nova, GraphQL, NuxtJs, Apollo and ...more
Stars: ✭ 54 (-96.99%)
Mutual labels:  graphql, laravel
Vue Relay
🖖 🔛 🗂 A framework for building GraphQL-driven Vue.js applications.
Stars: ✭ 105 (-94.14%)
Mutual labels:  graphql, relay
Relay Rails Blog
A graphql, relay and standard rails application powered demo weblog. We are using Graphql server and relay for our react component data needs.
Stars: ✭ 140 (-92.19%)
Mutual labels:  graphql, relay
Relay Fullstack
☝️🏃 Modern Relay Starter Kit - Integrated with Relay, GraphQL, Express, ES6/ES7, JSX, Webpack, Babel, Material Design Lite, and PostCSS
Stars: ✭ 986 (-45.01%)
Mutual labels:  graphql, relay
Magiql
🌐 💫 Simple and powerful GraphQL Client, love child of react-query ❤️ relay
Stars: ✭ 45 (-97.49%)
Mutual labels:  graphql, relay
Hackatalk
TalkTalk renewal. Open source chat app built-in expo managed work flow
Stars: ✭ 123 (-93.14%)
Mutual labels:  graphql, relay

Laravel GraphQL


This package is no longuer maintained. Please use rebing/graphql-laravel or other Laravel GraphQL packages


Use Facebook GraphQL with Laravel 5 or Lumen. It is based on the PHP implementation here. You can find more information about GraphQL in the GraphQL Introduction on the React blog or you can read the GraphQL specifications. 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 Build Status Total Downloads


To use laravel-graphql with Relay, check the feature/relay branch.


Installation

Version 1.0 is released. If you are upgrading from older version, you can check Upgrade to 1.0.

Dependencies:

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

{
  "require": {
    "folklore/graphql": "~1.0.0"
  }
}

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

$ composer install

or

$ composer update

Laravel >= 5.5.x

1- Publish the configuration file

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

2- Review the configuration file

config/graphql.php

Laravel <= 5.4.x

1- Add the service provider to your config/app.php file

Folklore\GraphQL\ServiceProvider::class,

2- Add the facade to your config/app.php file

'GraphQL' => Folklore\GraphQL\Support\Facades\GraphQL::class,

3- Publish the configuration file

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

4- Review the configuration file

config/graphql.php

Lumen

1- Load the service provider in bootstrap/app.php

$app->register(Folklore\GraphQL\LumenServiceProvider::class);

2- For using the facade you have to uncomment the line $app->withFacades(); in bootstrap/app.php

After uncommenting this line you have the GraphQL facade enabled

$app->withFacades();

3- Publish the configuration file

$ php artisan graphql:publish

4- Load configuration file in bootstrap/app.php

Important: this command needs to be executed before the registration of the service provider

$app->configure('graphql');
...
$app->register(Folklore\GraphQL\LumenServiceProvider::class)

5- Review the configuration file

config/graphql.php

Documentation

Usage

Advanced Usage

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

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();
        }
    }
}

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

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

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."
        ]
      }
    }
  ]
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].