rebing / graphql-laravel Goto Github PK
View Code? Open in Web Editor NEWLaravel wrapper for Facebook's GraphQL
License: MIT License
Laravel wrapper for Facebook's GraphQL
License: MIT License
I have a problem with custom fields as the title says. I have tried to create a Image field, like in the docs
class ImageField extends Field {
protected $attributes = [
public function args()
{
return [
'width' => [
'type' => Type::int(),
'description' => 'Path to the image',
],
'height' => [
'type' => Type::int(),
'description' => 'Path to the image',
]
];
}
protected function resolve($root, $args)
{
$width = isset($args['width']) ? $args['width']:100;
$height = isset($args['height']) ? $args['height']:100;
return 'http://placehold.it/'.$width.'x'.$height;
}
}
My problem is; How do i pass arguments to this class? I can't find an example of how this is done in the docs.
Thanks in advance.
I'm having some trouble installing this library with composer on a laravel 5.4.*. I think it has something to do with the composer file on this repo. My installation fails with this line:
"laravel/laravel": "^5.1"
Isn't it better to have:
"laravel/framework": "^5.1",
I might be wrong but i just find i weird that we need to install the whole folder structure and not just the core.
hi @rebing
i using Laravel Framework 5.4.19 for my project and use your package version dev-master
i try get relation with
public function resolve($root, $args, SelectFields $fields)
{
return User::with($fields->getRelations())->select($fields->getSelect())->get();
}
$this->getRelations()
not get join model but if i harcode with name join table it working
any solution for it?
thanks
Is there a reason you didn't just submit PR's to the original laravel-graphql
project? It looks like you're implementing some great new features, but this project has much less visibility, which means it's likely to get less bugfix contributions/etc. Why not combine efforts?
GraphQL::addQuery and GraphQL::addMutation are missing.
I know this library is only for Laravel, but I think it wouldn't be a big issue to make it works also with Lumen. Now it throws:
PHP Fatal error: Uncaught ReflectionException: Class path.storage does not exist in /Users/VojtaSvoboda/Www/test/vendor/laravel/framework/src/Illuminate/Container/Container.php:752
But when you add these two lines to bootstrap.app
:
$app->instance('path.config', app()->basePath() . DIRECTORY_SEPARATOR . 'config');
$app->instance('path.storage', app()->basePath() . DIRECTORY_SEPARATOR . 'storage');
it works well. But it would be better to works without these two lines, be default.
"Custom middleware can be defined for each query/mutation" from the docs
I can see you write this in the docs, but I can't figure out how this works:
I would like to have the same endpoint, but just remove auth from the LoginMutation::class is this possible or what is the recommendation in this scenario?
'schemas' => [
'default' => [
'query' => [
'cases' => App\GraphQL\Order\CaseQuery::class,
'caseType' => App\GraphQL\CaseType\CaseTypeQuery::class
],
'mutation' => [
'case' => CreateCaseMutation::class,
'login' => LoginMutation::class
],
'middleware' => ['auth']
],
],
When i try to push the configuration with:
php artisan vendor:publish --provider="Rebing\GraphQL\GraphQLServiceProvider"
I get the error:
[ReflectionException]
Class Rebing\GraphQL\Console\TypeMakeCommand does not exist
I'm using laravel framework 5.4
Is the statement in the title correct? they mean the same thing?
What is the current version of the repository in https://packagist.org/packages/rebing/graphql-laravel ?
Why at packagist.org written:
composer require rebing / graphql-laravel
http://take.ms/bv7tD and it works fine..
But in Readme.md of https://github.com/rebing/graphql-laravel :
{
"Require": {
"Rebing / graphql": "^ 1.0"
}
}
Composer can not find the package "Rebing / graphql"
Hello again.
Thanks for the library.
I can't find the documentation on how to manually return errors.
By default GraphQL has it's own errors it will return but what if I wanted to do something with a query or mutation and return my own error message, or just a basic error message instead of
returning null which is what I've been doing. How do I go about it? Thanks again.
I'm trying to use the pagination but i can't understand how it works.
i tried two things:
return Type::listOf(GraphQL::paginate('user'));
but i get Cannot query field "id" on type "user_pagination"
return Type::listOf(GraphQL::paginate('user','user'));
it's working but it's not returning the getPaginationFields()
this is my UserQuery code:
<?php
namespace App\GraphQL\Query;
use App\User;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\ResolveInfo;
use Rebing\GraphQL\Support\SelectFields;
use Rebing\GraphQL\Support\Query;
use Rebing\GraphQL\Support\Facades\GraphQL;
class UsersQuery extends Query
{
protected $attributes = [
'name' => 'Users',
'description' => 'A query'
];
public function type()
{
return Type::listOf(GraphQL::paginate('user'));
}
public function args()
{
return [
'id' => [
'name' => 'id',
'type' => Type::string()
],
'name' => [
'name' => 'name',
'type' => Type::string()
],
'email' => [
'name' => 'email',
'type' => Type::string()
],
'limit' => [
'name' => 'limit',
'type' => Type::INT(),
],
'page' => [
'name'=> 'page',
'type'=>Type::INT()
]
];
}
public function resolve($root, $args, SelectFields $fields)
{
$query = User::query();
$query->with($fields->getRelations());
$query->select($fields->getSelect());
if( isset($args['limit']) )
{
$page = $args['page'] ?? 1;
return $query->paginate($args['limit'], ['*'], 'page', $page);
}
return $query->get();
}
}
class CaseType extends GraphQLType {
protected $attributes = [
'name' => 'Case',
'description' => 'A Case',
'model' => Order::class,
];
public function fields()
{
return [
'id' => [
'type' => Type::nonNull(Type::int()),
'description' => 'The id of the user',
],
'case_number' => [
'type' => Type::nonNull(Type::string()),
'description' => 'An unique identifier for the case',
'alias' => 'number'
],
'caseType' => [
'type' => GraphQL::type('caseType'),
'description' => 'type of case',
'alias' => 'type'
]
];
}
}
I would like to implement a alias function.
The output will send the alias instead of the key.
The input will receive the alias and convert it to the correct key value, so the queries will work correctly
Would you be interested in merging a pullrequest with that functionality?
Declaration of XX\GraphQL\Mutation\TestMutation::rules() should be compatible with Rebing\GraphQL\Support\Mutation::rules(array $args)
when rollback to1.8.0 there is no error.
please advice.
I need rename field in query and in backend rename to field
Same Laravel Fractal
Example:
My table users: Columns: Id, Name , Email
Request:
query Users { users{ code nick contact} }
I dont need exposed the field from my database ..
Any ideas?
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Conclusion: remove laravel/laravel dev-master
- rebing/graphql-laravel 1.1 requires laravel/laravel ^5.1 -> satisfiable by laravel/laravel[5.1.x-dev, 5.2.x-dev, 5.3.x-dev, v5.1.0, v5.1.1, v5.1.11, v5.1.3, v5.1.33, v5.1.4, v5.2.0, v5.2.15, v5.2.23, v5.2.24, v5.2.27, v5.2.29, v5.2.31, v5.3.0, v5.3.10, v5.3.16, v5.3.30, v5.4.0, v5.4.15, v5.4.3, v5.4.9].
- rebing/graphql-laravel 1.1.2 requires laravel/laravel ^5.1 -> satisfiable by laravel/laravel[5.1.x-dev, 5.2.x-dev, 5.3.x-dev, v5.1.0, v5.1.1, v5.1.11, v5.1.3, v5.1.33, v5.1.4, v5.2.0, v5.2.15, v5.2.23, v5.2.24, v5.2.27, v5.2.29, v5.2.31, v5.3.0, v5.3.10, v5.3.16, v5.3.30, v5.4.0, v5.4.15, v5.4.3, v5.4.9].
- rebing/graphql-laravel v1.1.1 requires laravel/laravel ^5.1 -> satisfiable by laravel/laravel[5.1.x-dev, 5.2.x-dev, 5.3.x-dev, v5.1.0, v5.1.1, v5.1.11, v5.1.3, v5.1.33, v5.1.4, v5.2.0, v5.2.15, v5.2.23, v5.2.24, v5.2.27, v5.2.29, v5.2.31, v5.3.0, v5.3.10, v5.3.16, v5.3.30, v5.4.0, v5.4.15, v5.4.3, v5.4.9].
- Can only install one of: laravel/laravel[dev-master, 5.1.x-dev].
- Can only install one of: laravel/laravel[dev-master, 5.2.x-dev].
- Can only install one of: laravel/laravel[dev-master, 5.3.x-dev].
- Can only install one of: laravel/laravel[v5.1.0, dev-master].
- Can only install one of: laravel/laravel[v5.1.1, dev-master].
- Can only install one of: laravel/laravel[v5.1.11, dev-master].
- Can only install one of: laravel/laravel[v5.1.3, dev-master].
- Can only install one of: laravel/laravel[v5.1.33, dev-master].
- Can only install one of: laravel/laravel[v5.1.4, dev-master].
- Can only install one of: laravel/laravel[v5.2.0, dev-master].
- Can only install one of: laravel/laravel[v5.2.15, dev-master].
- Can only install one of: laravel/laravel[v5.2.23, dev-master].
- Can only install one of: laravel/laravel[v5.2.24, dev-master].
- Can only install one of: laravel/laravel[v5.2.27, dev-master].
- Can only install one of: laravel/laravel[v5.2.29, dev-master].
- Can only install one of: laravel/laravel[v5.2.31, dev-master].
- Can only install one of: laravel/laravel[v5.3.0, dev-master].
- Can only install one of: laravel/laravel[v5.3.10, dev-master].
- Can only install one of: laravel/laravel[v5.3.16, dev-master].
- Can only install one of: laravel/laravel[v5.3.30, dev-master].
- Can only install one of: laravel/laravel[v5.4.0, dev-master].
- Can only install one of: laravel/laravel[v5.4.15, dev-master].
- Can only install one of: laravel/laravel[v5.4.3, dev-master].
- Can only install one of: laravel/laravel[v5.4.9, dev-master].
- Installation request for laravel/laravel dev-master -> satisfiable by laravel/laravel[dev-master].
- Installation request for rebing/graphql-laravel ^1.1 -> satisfiable by rebing/graphql-laravel[1.1, 1.1.2, v1.1.1].
Installation failed, reverting ./composer.json to its original content.
When using composer require rebing/graphql-laravel:"~1.7"
it removes me all Laravel libraries and project is not possible to start the project:
composer require rebing/graphql-laravel:"~1.7"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 4 installs, 1 update, 23 removals
- Removing illuminate/auth (v5.5.17)
- Removing illuminate/broadcasting (v5.5.17)
- Removing illuminate/bus (v5.5.17)
- Removing illuminate/cache (v5.5.17)
- Removing illuminate/config (v5.5.17)
- Removing illuminate/console (v5.5.17)
- Removing illuminate/container (v5.5.17)
- Removing illuminate/contracts (v5.5.17)
- Removing illuminate/database (v5.5.17)
- Removing illuminate/encryption (v5.5.17)
- Removing illuminate/events (v5.5.17)
- Removing illuminate/filesystem (v5.5.17)
- Removing illuminate/hashing (v5.5.17)
- Removing illuminate/http (v5.5.17)
- Removing illuminate/pagination (v5.5.17)
- Removing illuminate/pipeline (v5.5.17)
- Removing illuminate/queue (v5.5.17)
- Removing illuminate/routing (v5.5.17)
- Removing illuminate/session (v5.5.17)
- Removing illuminate/support (v5.5.17)
- Removing illuminate/translation (v5.5.17)
- Removing illuminate/validation (v5.5.17)
- Removing illuminate/view (v5.5.17)
- Installing ramsey/uuid (3.7.1): Loading from cache
- Installing league/flysystem (1.0.41): Loading from cache
- Updating laravel/framework (v5.5.17 => v5.5.17): Downloading (100%)
- Installing webonyx/graphql-php (v0.10.2): Loading from cache
- Installing rebing/graphql-laravel (v1.7.2): Loading from cache
PHP 7.1.x, Lumen 5.5.2, MacOS.
When I delete existing composer.lock and try composer install
, it works well.
Hello, thanks again for the package. I tried to use the Type Relationship Query functionality as specified in the example. It didn't work. I tried several variations of ways as well to make sure it wasn't just a one-off scenario. I never got the Type Relationship Query to work.
Thanks.
Hi there,
I would like to ask you what do you mean by:
// Uses the 'scopeIsMe' function on our custom User model
In your example in readme is isMe
defined as boolean, but eloquent scope methods should always return queries. So how would you implement scopeIsMe
on User model?
Thank you
Giving it is a fork form Folkloreatelier/laravel-graphql i'm not sure what is the difference, or the purpose of it.
Could you clarified it?
Lets say a schema has a middleware A. Is it possible to change that middleware only for one mutation in that schema to middleware B?
#FIRST ISSUE
When am creating a mutation that receives the following (where id a the top level is required, while id at the nested object is sometimes required, the top level validation fails unless I renamed the inner object 'id' key to something else.
Also, how to set validation rules for input object type args ?
For example, I am trying to mutate an object with the following 3 properties (1 property is an input object type)
id - required (Int)
name -sometimes required (String)
subjects - sometimes required(InputObjectType), but if present{
}
{ "id": 1, "name": "Samle Content 1", "subjects": [ { "id": : 1, "name": "Sample content 2", }, {"name": "Sample Content 3"} ] }
My args() and rules() function in the mutation looks like the following. However I am not sure where to specify the validation rules for the InputObjectType
`
public function args(){
return [
'id' => [
'name' => 'id',
'type' => Type::int(),
],
'name' => [
'name' => 'name',
'type' => Type::string(),
],
'subjects' => [
'name' => 'subjects',
'type' => Type::listOf(new InputObjectType([
'name' => 'UpdateClassroomSubjectInput',
'fields' => [
'id' => [
'type' => Type::int(),
'description' => 'The id of the subject'
],
'name' => [
'type' => Type::string(),
'description' => 'The name of the subject'
]
]
]))
]
//'subjects' => Type::listOf( new \App\GraphQL\InputTypes\ClassroomSubjectInputType)
];
}`
`
public function rules(){
return [
'id' => [
'required'
],
'name' => [
'sometimes',
'required'
],
'subjects' => [
'sometimes',
'required'
//How to specify the nested object validation rules here ? Or should I simply validate them in the resolver ?
]
];
}
`
#SECOND ISSUE
It doesn't seem there is a way to create a class name for input object types and reuse them in different mutations ( just like the field classes), The config file has no options to provide a list of input object types that can be loaded in the schema ( like the types or mutation list)
I've got a category table with the field category_id which represents which category the current category belongs to (it's parent).
However, I get this error when I run a query where I include parent:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.parent_id' in 'field list' (SQL: select `categories`.`id`, `categories`.`parent_id` from `categories` limit 1)
In my Category Model I have the following method:
function parent() {
return $this->belongsTo('App\Category');
}
This is the portion in my CategoryType
'parent' => [
'type' => GraphQL::type('category'),
'description' => 'The parent category of this category'
],
Any help would be greatly appreciated!
I was stuck for several hours on how to pass in dynamic variables because by default it was set to params when the default for most of the applications I know is variables.
Why not just leave it as the default which I'm assuming is variables considering I came from folklore's library to this and that worked fine.
Such stress. Man.
Is there a way to connect queries and or mutations to controllers in the http? Or with graphql the are obsolete?
I am trying to set up a query on a tree-structure of Page type objects:
query{
pages{
id,
sorting,
children{
id,
sorting
}
}
}
The table representing pages does not have a nicely named column for sorting, but uses "sub_cat".
I want the field named sorting in the output so I have specified a sorting field in the schema for Page and specified a resolveSortingField($root, $args) function which return $root->sub_cat. for the Page type so that it is output as Sorting and not sub_cat.
This works fine for "flat" queries, however it results in a problem when I eager-load children using ::with($fields->getRelations()) (Rebing\GraphQL\Support\SelectFields) since this ends up creating an eager load query with a SELECT part using the fields names directly from the query, which of course gives an error:
select sites
.id
, sites
.sorting
from sites
where sites
.id
in (0, 1, 5))
Is there any way of configuring the type or query to get around this problem?
As @inxilpro also pointed out in #12 that it's a fork from the original laravel-graphql package. Maybe we can collaboratively port all of these changes back to the original and bigger repository? As I haven't had any experience with the original project I am not aware of all the differences. But it doesn't seem wise in the long run to develop two packages with a similar purpose before trying to combine efforts.
Maybe we can start by listing all the differences in the two packages? Then we can analyze how difficult would it be to port these changes back to the original repo? Additionally are there any incompatibilities with these two repos or has the original implemented some breaking changes? For some differences maybe we can simply make the original repository somehow more extensible but to keep the main logic in one place. I would be more than happy to help with the PR-s to the "Folkloreatelier/laravel-graphql" but I would first like to understand all the differences.
Maybe @rebing (and also @dmongeau) can comment on this subject?
I have a relation on a model to get all "neighbouring" models, with the same parent_id.
public function related()
{
return $this->hasMany(self::class, 'parent_id', 'parent_id');
}
Both keys should most likely be added automatically to select, so Laravel can later join related models, but neither get automatically added.
First key on the base-model I could add like this:
'related' => [
'always' => ['parent_id'],
…
]
The second key for the retrieved model doesn't get added automatically, so Laravel will eventually return an empty array of related objects.
I have narrowed down the issue to be somewhere around SelectFields:176
. And for my current case I was able to fix it by adding a condition after $field[$foreignKey] = self::FOREIGN_KEY;
:
$field[$foreignKey] = self::FOREIGN_KEY;
if( ! in_array($foreignKey, $select))
{
$select[] = $foreignKey;
}
But with the lack of tests I am unsure if this is the correct solution or if it will break something else.
Good day!
Interested in the ability to upload files to the graph
Who faced such a need and what implementation options are there?
Another issue with the same setup as in: #16
I have pagination working correctly and it's and awesome feature!
It works for users and devices separately.
But now I want to query all the devices of a user - with pagination. Like this:
{
users {
data {
id
devices {
data {
id
}
total
}
}
total
}
}
Here you can see an example in the graphQL docs.
I tried to change the relation in the UserType
'type' => Type::listOf(GraphQL::type('Device'))
'type' => GraphQL::paginate('Device')
.This gives me the error because I use it in the DeviceType Definition
Schema must contain unique named types but contains multiple types named \"Device_pagination\".
I also tried to change it
'type' => GraphQL::type('Device_pagination')
But this gives me the error: Type Device_pagination not found.
Is there a way to enable those kind of queries?
Thanks for your help.
The paginate function always returns a new type, which makes re-use impossible on edges.
Possible fix is to immitate GraphQl::type() check:
public function paginate($typeName, $customName = null)
{
$name = $customName ?: $typeName . '_pagination';
if(!isset($this->typesInstances[$name]))
{
$this->typesInstances[$name] = new PaginationType($typeName, $customName);
}
return $this->typesInstances[$name];
}
Hi there,
Trying to migrate from Folklore to your forked version as I need stuff like privacy and authorization. And while most work I'm running into an issue when i use a Type::listOf(Type::string()) on one of my arguments in a mutation.
I've tried to backtrace it and it seems to be in the SelectFields.php on line 123 there is a call to a method that doesn't exist, I looked in Folklore's lib to see if I could get it from there but it turns out this file doesn't even exist there.
Any chance you can help me figure out what going wrong?
`<?php
namespace App\GraphQL\Mutation;
use GraphQL;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Mutation;
use App\Wishlist;
use Illuminate\Support\Facades\DB;
class AttachWishesToWishlistMutation extends Mutation
{
protected $attributes = [
'name' => 'attachWishesToWishlist'
];
public function type()
{
return GraphQL::type('Wishlist');
}
public function args()
{
return [
'wishId' => ['name' => 'wishId', 'type' => Type::listOf(Type::string())],
'wishlistId' => ['name' => 'wishlistId', 'type' => Type::string()],
];
}
public function rules()
{
return [
'wishId' => ['required'],
'wishlistId' => ['required'],
];
}
public function resolve($root, $args)
{
$wishlist = Wishlist::find($args['wishlistId']);
if (!$wishlist) {
return null;
}
if (isset($args['wishlistId'])) {
foreach ($args['wishId'] as $wishId) {
$exists = DB::table('wishlist_wishes')
->whereWishId($wishId)
->whereWishlistId($args['wishlistId'])
->count() > 0;
if(!$exists) {
$wishlist->wishes()->attach($wishId);
}
}
}
return $wishlist;
}
}`
It returns the following when using Rebing:
{ "data": { "attachWishesToWishlist": null }, "errors": [ { "message": "Call to undefined method GraphQL\\Type\\Definition\\ListOfType::getField()", "locations": [ { "line": 2, "column": 3 } ] } ] }
But if i simply change the Mutation import to Folklore it get the correct data. I'd gladly help out fixing it if you can guide me in the right direction.
It seems to be this piece of code that is having issues:
// If field doesn't exist on definition we don't select it try { $fieldObject = $parentType->getField($key); } catch (InvariantViolation $e) { continue; }
I want to use GraphQL to be layer on top of our existing REST based API. In this setup we have to write raw queries that includes complex business logic.
Could you provide an example of how I can setup this library to run standard queries using DB::raw()
(or equivalent)?
I'm not sure if this is an issue or by design but I feel like the functionality should be slightly different. If you override the query for a relation field, the arguments that get passed are the parents, not that subqueries arguments.
Let's say I have the following GraphQL query:
query {
student(id: 10) {
firstName
lastName
classes(week: "2017-10-07") {
title
}
}
}
And have the following corresponding fields:
//...
public function fields()
{
return [
// ...
'classes' => [
'type' => GraphQL::type('class'),
'args' => [
'week' => [
'type' => Type::string(),
'name' => 'week'
]
],
'query' => function(array $args, $query) {
// $args are the arguments for `student` not for `class`
}
]
];
}
The arguments that are passed to the query are those for student
, not those for classes
.
However if instead I use a custom resolver like so:
//...
public function fields()
{
return [
// ...
'classes' => [
'type' => GraphQL::type('class'),
'args' => [
'week' => [
'type' => Type::string(),
'name' => 'week'
]
],
'resolve' => function ($root, $args) {
// $args now pass in `week` correctly
}
]
];
}
Then the $args
variable correctly contains week
. Is there a reason why the two sets of arguments differ? I feel like if anything they should both contain both so that a resolver can get its parents arguments and its own. In my particular case the use case I want is to be able to add constraints to the relation for a date range based on the arguments passed in to classes
. Using the query builder is more efficient than having to use the resolver.
I was using Folkloreatelier relay branch ...but I saw rebing and I wanted to use it
after I remove Folkloreatelier and it is confing file and installed rebing it did not work !
it gives me error after accessing graphql url -> MethodNotAllowedHttpException ...
in RouteCollection.php (line 251)
at RouteCollection->methodNotAllowed(array('POST'))in RouteCollection.php (line 238)
at RouteCollection->getRouteForMethods(object(Request), array('POST'))in RouteCollection.php (line 176)
at RouteCollection->match(object(Request))in Router.php (line 546)
at Router->findRoute(object(Request))in Router.php (line 525)
at Router->dispatchToRoute(object(Request))in Router.php (line 511)
at Router->dispatch(object(Request))in Kernel.php (line 176)
at Kernel->Illuminate\Foundation\Http{closure}(object(Request))in Pipeline.php (line 30)
at Pipeline->Illuminate\Routing{closure}(object(Request))in HandleCors.php (line 34)
at HandleCors->handle(object(Request), object(Closure))in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline{closure}(object(Request))in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing{closure}(object(Request))in CheckForMaintenanceMode.php (line 46)
at CheckForMaintenanceMode->handle(object(Request), object(Closure))in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline{closure}(object(Request))in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing{closure}(object(Request))in Request.php (line 111)
at Request->handle(object(Request), object(Closure))in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline{closure}(object(Request))in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing{closure}(object(Request))in Pipeline.php (line 102)
at Pipeline->then(object(Closure))in Kernel.php (line 151)
at Kernel->sendRequestThroughRouter(object(Request))in Kernel.php (line 116)
at Kernel->handle(object(Request))in index.php (line 53)
I followed an example at https://medium.com/skyshidigital/easy-build-api-using-laravel-and-graphql-67e2c5c5e150
I'm getting the following error, can you help pinpoint where the issue is?
There appear to be an issue with the ->select() method when used in Query type.
I have a User model having hasMany(Example::class) relationship.
This return empty examples array.
User::with(array_keys($fields->getRelations()))
->where($where)
->select($fields->getSelect())
->paginate();
But removing ->select($fields->getSelect()) return my entire examples array.
User::with(array_keys($fields->getRelations()))
->where($where)
->paginate();
The issue could be related to the Laravel :with() method, because adding specific columns in :with() also yield the same bug.
Route::get('/', function () {
// examples return full array list.
return App\User::with("examples")->where("id", 5)->first();
// examples return empty array
return App\User::with("examples:id,name")->where("id", 5)->first();
});
Platform
MacOS
Valet
Laravel Framework 5.5.19
rebing/graphql-laravel ~1.7
hi, i'm asking how to implement multiple schema and use it using graphiQL, in documentation it's look like this
'schema' => 'default_schema',
'schemas' => [
'default' => [
'query' => [
'example_query' => ExampleQuery::class,
],
'mutation' => [
'example_mutation' => ExampleMutation::class,
],
],
'user' => [
'query' => [
'profile' => 'App\GraphQL\Query\ProfileQuery'
],
'mutation' => [
],
'middleware' => ['auth'],
],
],
my question are,
is route should look like this?
Route::post('graphql/{schema_name}/query', ['as' => 'api.graphql.query', 'uses' => '\Rebing\GraphQL\GraphQLController@query']);
and should i point my graphiQL to specific schema route?
If an object has some properties that have been defined using accessors (inside a model) instead of an eloquent relationship, and those properties do return the expected object class or an expected collection of objects. This GraphQL package is not able to map those objects as it is expecting an eloquent query builder class
Hey!
I couldn't find any documentation on dynamic rules. For example when as an argument I'm accepting a field as an array, I'd perhaps like to apply rules for the whole array. For that I would need to access $args
in the rules
method. Is there a way to do this now already or would it be something new?
Thanks for an awesome package boi.
I've been trying out graphql with laravel and I was wondering how should I approach pivots in eloquent?
This package can handle something like:
'posts' => [
'type' => Type::listOf(GraphQL::type('Post')),
'description' => 'The user posts',
// Can also be defined as a string
'always' => ['title', 'body'],
]
But when it comes to belongsToMany
relationships how should I attach withPivot
columns in graphql?
I have a problem accessing fields in types implementing an interface.
I have a simple interface 'TestInterface' defining fields type and field1. I have an object TestObject implementing the interface and defining the fields type, field1 and field2.
I have a simple query returning a list of TestInterface type objects.
The schema generates correctly and looks fine (inspecting in graphiql).
I do a simple query to confirm that types are being resolved correctly:
{
Tests{
__typename
field1
}
}
which is confirmed in result:
{
"data": {
"Tests": [
{
"__typename": "TestObject",
"field1": "asd"
},...
]
}
}
However if I try to query field2, which is defined on TestObject (but not in the interface):
{
Tests{
__typename
field1
... on TestObject {field2}
}
}
I get the following: Field "field2" is not defined for type "TestInterface"
So even though the first query confirms that the return is of concrete type TestObject, for some reason it tries to resolve field2 on TestInterface.
How can we use this with laravel eloquent polymorphic relationship?
I think I have managed to fill in some of the holes, but I am completely lost. for some reason it completely ignores the limit and page args i pass through the query. Could you clarify?
<?php
namespace App\GraphQL\Query;
use GraphQL;
use GraphQL\Type\Definition\Type as Type;
use \Rebing\GraphQL\Support\Query;
use App\Models\CourtCase;
use Rebing\GraphQL\Support\SelectFields;
use GraphQL\Type\Definition\ResolveInfo;
class CourtCaseQuery extends Query
{
protected $attributes = [
'name' => 'CourtCaseQuery',
'description' => 'A query',
];
public function type()
{
return GraphQL::paginate('Cases');
}
public function args()
{
return [
'id' => ['name' => 'id', Type::id()],
'name' => ['name' => 'name', Type::string()],
'court_id' => ['name' => 'court_id',Type::id()],
'limit' => ['name'=> 'limit','type'=>Type::INT()],
'page' => ['name'=> 'page','type'=>Type::INT()]
];
}
public function resolve($root, $args, SelectFields $fields)
{
$courtCase = CourtCase::query();
$courtCase->with($fields->getRelations())->select($fields->getSelect());
if (isset($args['id']))
{
//$cases->where('id',$args['id']);
$courtCase->where('id', $args['id']);
}
if (isset($args['court_id']))
{
//Log::info('court_id set');
$courtCase->where('court_id',$args['court_id']);
}
return $courtCase->with($fields->getRelations())->select($fields->getSelect())->paginate();
}
}
Another question. I was trying to build a search query that goes through multiple models. I was looking at this GraphQL Type: https://github.com/webonyx/graphql-php/blob/master/docs/type-system/unions.md
Is it possible to implement this using this package?
Basically, this is what I want to achieve:
https://medium.com/the-graphqlhub/graphql-tour-interfaces-and-unions-7dd5be35de0d
Cheers!
Hi,
I try install your package and I have problem with composer:
Using version ^1.5 for rebing/graphql-laravel
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Installation request for rebing/graphql-laravel ^1.5 -> satisfiable by rebing/graphql-laravel[v1.5.0].
- Conclusion: remove webonyx/graphql-php v0.10.2
- Conclusion: don't install webonyx/graphql-php v0.10.2
- rebing/graphql-laravel v1.5.0 requires webonyx/graphql-php ~0.9.0 -> satisfiable by webonyx/graphql-php[v0.9.0, v0.9.1, v0.9.10, v0.9.11, v0.9.12, v0.9.13, v0.9.14, v0.9.2, v0.9.3, v0.9.4, v0.9.5, v0.9.6, v0.9.7, v0.9.8, v0.9.9].
- Can only install one of: webonyx/graphql-php[v0.9.0, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.1, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.10, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.11, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.12, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.13, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.14, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.2, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.3, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.4, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.5, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.6, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.7, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.8, v0.10.2].
- Can only install one of: webonyx/graphql-php[v0.9.9, v0.10.2].
- Installation request for webonyx/graphql-php (locked at v0.10.2) -> satisfiable by webonyx/graphql-php[v0.10.2].
I use laravel 5.5.
Could you help me?
I have the following relation:
User has many devices, and a device belongs to a user.
User has an id.
And a device has an user_id.
The following query will return the device information as desired:
{
users {
data {
id
firstname
devices {
id
}
}
}
}
This query wont find any information devices (when leaving out the id):
{
users {
data {
firstname
devices {
id
}
}
}
}
Is this part of the design?
Or is there a way where I don't need to query the foreign key (user.id) explicitly?
Currently the variable names have to exactly match the argument names.
Valid: query($id:Int){user(id:$id){...
Invalid: query($userId:Int){user(id:$userId){...
I would like to return the created_at
and updated_at
timestamps of a model entry. In my GraphQL Type I have added the following fields:
[
'created_at' => [
'type' => Type::string(),
],
'updated_at' => [
'type' => Type::string(),
],
]
If I query those, I receive null
. If I add custom resolve functions like this, it all works perfectly:
public function resolveCreatedAtField($root)
{
return (string) $root->created_at;
}
Note the prefix (string)
type, which is required.
Naturally I can add those two functions for every type I create, but this seems rather cumbersome. Is there something I am missing here, or is this a bug of some sorts?
Hi @rebing , please i need some help. i'm getting a "MethodNotAllowedHttpException" when i tried to make a query. i have check over and over the documentation and i can't find the possible mistake that is causing this Exception.
i was able to get GraphQL working this plugin https://github.com/Folkloreatelier/laravel-graphql and with Django+Graphene, but each time i try with this one, i get the same error.
On the file "conf/app.php", i added this on the "providers" array:
Rebing\GraphQL\GraphQLServiceProvider::class,
and this to the "aliases" array:
'GraphQL' => Rebing\GraphQL\Support\Facades\GraphQL::class,
this is my UsersQuery.php:
`<?php
namespace App\GraphQL\Query;
use App\User;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\ResolveInfo;
use Rebing\GraphQL\Support\SelectFields;
use Rebing\GraphQL\Support\Query;
use Rebing\GraphQL\Support\Facades\GraphQL;
class UsersQuery extends Query
{
protected $attributes = [
'name' => 'UsersQuery',
'description' => 'A query'
];
public function type()
{
return Type::listOf(GraphQL::type('user'));
}
public function args()
{
return [
'id' => [
'name' => 'id',
'type' => Type::string()
],
'username' => [
'name' => 'username',
'type' => Type::string()
],
'email' => [
'name' => 'email',
'type' => Type::string()
]
];
}
public function resolve($root, $args, SelectFields $fields, ResolveInfo $info)
{
if(isset($args['id']))
{
return User::where('id' , $args['id'])->get();
}
else if(isset($args['username']))
{
return User::where('username', $args['username'])->get();
}
else if(isset($args['email']))
{
return User::where('email', $args['email'])->get();
}
else
{
return User::all();
}
}
}`
this is my UsersType.php:
`<?php
namespace App\GraphQL\Type;
use App\User;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Folklore\GraphQL\Support\Type as GraphQLType;
class UsersType extends GraphQLType
{
protected $attributes = [
'name' => 'UsersType',
'description' => 'A User type',
'model' => User::class,
];
public function fields()
{
return [
'id' => [
'type' => Type::nonNull(Type::string()),
'description' => 'The id of the user'
],
'username' => [
'type' => Type::string(),
'description' => 'The username of user'
],
'email' => [
'type' => Type::string(),
'description' => 'The email of user'
],
'first_name' => [
'type' => Type::string(),
'description' => 'The first_name of user'
],
'last_name' => [
'type' => Type::string(),
'description' => 'The last_name 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);
}
} `
My graphql configuration is like this:
`<?php
use App\GraphQL\Query\UsersQuery;
use App\GraphQL\Type\UsersType;
return [
'prefix' => 'graphql',
'routes' => '{graphql_schema?}',
'controllers' => \Rebing\GraphQL\GraphQLController::class . '@query',
'middleware' => [],
'default_schema' => 'default',
'schemas' => [
'default' => [
'query' => [
'users' => UsersQuery::class
],
'mutation' => [
],
'middleware' => []
],
],
'types' => [
'user' => UsersType::class
],
'error_formatter' => ['\Rebing\GraphQL\GraphQL', 'formatError'],
'params_key' => 'params',
];`
if someone sees somethng wrong please let me know!
thanks in advance for any help
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.