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.
Version 1.0 is released. If you are upgrading from older version, you can check Upgrade to 1.0.
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
1- Publish the configuration file
$ php artisan vendor:publish --provider="Folklore\GraphQL\ServiceProvider"
2- Review the configuration file
config/graphql.php
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
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
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}}
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}}
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}}
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."
]
}
}
]
}
概述 对于前后端分离的应用,跨域请求是个绕不过去的坎。接下来的 API 系列教程中,学院君将会推出基于 Vue + Laravel + GraphQL 实现的前后端分离的博客应用,这里面自然也涉及到大量跨域请求,跨域请求的解决方案有 CORS 和 JSONP(了解更多明细可以参考这篇教程),但是 JSONP 有个致命缺点 —— 仅支持 GET 请求,所以推荐使用 CORS(Cross-origin
namespace App\GraphQL\Query; use Folklore\GraphQL\Support\Query; use GraphQL\Type\Definition\ResolveInfo; use GraphQL\Type\Definition\Type; use GraphQL; use App\User; class UsersQuery extends Query{ p
导语 接上一篇文章末尾抛出的问题,在多表用户的情况下,一个守卫对应的一个资源提供者势必不能够满足要求了。这个时候最直观的操作就是增加守卫及其对应的资源提供者,用来对这个新数据表进行验证。 接下来是很重要的一段话,请仔细阅读: 当两个守卫(本文以user和admin为例)所对应的资源提供者不同时(分别对应Model\User,\Model\admin),假设分别以两表中id为1的记录生成token,
Laravel 是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来;它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁、富于表达力。 功能特点 1、语法更富有表现力 你知道下面这行代码里 “true” 代表什么意思么? $uri = Uri::create(‘some/uri’, array(), array(), tr
我需要空间/Laravel权限的帮助。当我试图分配它给我错误哎呀,看起来像出了问题。 错误 Connection.php第761行中的QueryExcema:SQLSTATE[23000]:完整性约束冲突:1048列role_id不能为空(SQL:插入到(,)值(9,))
Laravel 作为现在最流行的 PHP 框架,其中的知识较多,所以单独拿出来写一篇。 简述 Laravel 的生命周期 Laravel 采用了单一入口模式,应用的所有请求入口都是 public/index.php 文件。 注册类文件自动加载器 : Laravel通过 composer 进行依赖管理,无需开发者手动导入各种类文件,而由自动加载器自行导入。 创建服务容器:从 bootstrap/ap
简介 Laravel Scout 为 Eloquent 模型 全文搜索提供了简单的,基于驱动的解决方案。通过使用模型观察者,Scout 会自动同步 Eloquent 记录的搜索索引。 目前,Scout 自带一个 Algolia 驱动;不过,编写自定义驱动很简单, 你可以轻松的通过自己的搜索实现来扩展 Scout。 安装 首先,通过 Composer 包管理器来安装 Scout: composer
简介 Laravel 致力于让整个 PHP 开发体验变得愉快, 包括你的本地开发环境。 Vagrant 提供了一种简单,优雅的方式来管理和配置虚拟机。 Laravel Homestead 是一个官方预封装的 Vagrant box,它为你提供了一个完美的开发环境,而无需在本地机器安装 PHP 、Web 服务器和其他服务器软件。不用担心会搞乱你的操作系统!Vagrant boxes 是一次性的。如果
WebStack-Laravel 一个开源的网址导航网站项目,具备完整的前后台,您可以拿来制作自己的网址导航。 部署 克隆代码: git clone https://github.com/hui-ho/WebStack-Laravel.git 安装依赖: composer installphp artisan key:generate 编辑配置: cp .env.example .env ...D