PHP code example of studio-net / laravel-graphql

1. Go to this page and download the library: Download studio-net/laravel-graphql library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

studio-net / laravel-graphql example snippets


# app/GraphQL/Definition/UserDefinition.php

namespace App\GraphQL\Definition;

use StudioNet\GraphQL\Definition\Type;
use StudioNet\GraphQL\Support\Definition\EloquentDefinition;
use StudioNet\GraphQL\Filter\EqualsOrContainsFilter;
use App\User;
use Auth;

/**
 * Specify user GraphQL definition
 *
 * @see EloquentDefinition
 */
class UserDefinition extends EloquentDefinition {
	/**
	 * Set a name to the definition. The name will be lowercase in order to
	 * retrieve it with `\GraphQL::type` or `\GraphQL::listOf` methods
	 *
	 * @return string
	 */
	public function getName() {
		return 'User';
	}

	/**
	 * Set a description to the definition
	 *
	 * @return string
	 */
	public function getDescription() {
		return 'Represents a User';
	}

	/**
	 * Represents the source of the data. Here, Eloquent model
	 *
	 * @return string
	 */
	public function getSource() {
		return User::class;
	}

	/**
	 * Which fields are queryable ?
	 *
	 * @return array
	 */
	public function getFetchable() {
		return [
			'id'          => Type::id(),
			'name'        => Type::string(),
			'last_login'  => Type::datetime(),
			'is_admin'    => Type::bool(),
			'permissions' => Type::json(),

			// Relationship between user and posts
			'posts'       => \GraphQL::listOf('post')
		];
	}

	/**
	 * Which fields are filterable ? And how ?
	 *
	 * @return array
	 */
	public function getFilterable() {
		return [
			'id'       => new EqualsOrContainsFilter(),
			"nameLike" => function($builder, $value) {
				return $builder->whereRaw('name like ?', $value),
			},
		];
	}

	/**
	 * Resolve field `permissions`
	 *
	 * @param  User $user
	 * @return array
	 */
	public function resolvePermissionsField(User $user) {
		return $user->getPermissions();
	}

	/**
	 * Which fields are mutable ?
	 *
	 * @return array
	 */
	public function getMutable() {
		return [
			'id'          => Type::id(),
			'name'        => Type::string(),
			'is_admin'    => Type::bool(),
			'permissions' => Type::array(),
			'password'    => Type::string()
		];
	}
}

# config/graphql.php

return [
	// ...
	'definitions' => [
		\App\GraphQL\Definition\UserDefinition::class,
		\App\GraphQL\Definition\PostDefinition::class
	],
	// ...
]

# app/GraphQL/Query/Viewer.php

namespace App\GraphQL\Query;

use StudioNet\GraphQL\Support\Definition\Query;
use Illuminate\Support\Facades\Auth;
use App\User;
use Auth;

class Viewer extends Query {
	/**
	 * {@inheritDoc}
	 */
	protected function authorize(array $args) {
		// check, that user is not a guest
		return !Auth::guest();
	}

	/**
	 * {@inheritDoc}
	 */
	public function getRelatedType() {
		return \GraphQL::type('user');
	}
	
	/**
	 * {@inheritdoc}
	 */
	public function getSource() {
		return User::class;
	}

	/**
	 * Return logged user
	 *
	 * @return User|null
	 */
	public function getResolver($opts) {
		return Auth::user();
	}
}

# config/graphql.php

return [
	'schema' => [
		'definitions' => [
			'default' => [
				'query' => [
					'viewer' => \App\GraphQL\Query\Viewer::class
				]
			]
		]
	],

	'definitions' => [
		\App\GraphQL\Definition\UserDefinition::class
	]
];

# app/GraphQL/Mutation/Profile.php

namespace App\GraphQL\Mutation;

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

class Profile extends Mutation {
	/**
	 * {@inheritDoc}
	 */
	protected function authorize(array $args) {
		// check, that user is not a guest
		return !Auth::guest();
	}

	/**
	 * {@inheritDoc}
	 *
	 * @return ObjectType
	 */
	public function getRelatedType() {
		return \GraphQL::type('user');
	}

	/**
	 * {@inheritDoc}
	 */
	public function getArguments() {
		return [
			'id'      => ['type' => Type::nonNull(Type::id())],
			'blocked' => ['type' => Type::string()]
		];
	};

	/**
	 * Update user
	 *
	 * @param  mixed $root
	 * @param  array $args
	 *
	 * @return User
	 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
	 */
	public function getResolver($root, array $args) {
		$user = User::findOrFail($args['id']);
		$user->update($args);

		return $user;
	}
}

# config/graphql.php

return [
	'schema' => [
		'definitions' => [
			'default' => [
				'query' => [
					'viewer' => \App\GraphQL\Query\Viewer::class
				],
				'mutation' => [
					'viewer' => \App\GraphQL\Mutation\Profile::class
				]
			]
		]
	],

	'definitions' => [
		\App\GraphQL\Definition\UserDefinition::class
	]
];

namespace App/GraphQL/Pipe;

use Closure;
use Illuminate\Database\Eloquent\Builder;

class OnlyAuthored {
	/**
	 * returns only posts that the viewer handle
	 *
	 * @param  Builder $builder
	 * @param  Closure $next
	 * @param  array $opts
	 * @return \Illuminate\Database\Eloquent\Model
	 */
	public function handle(Builder $builder, Closure $next, array $opts) {
		$builder->where('author_id', $opts['context']->getKey());

		return $next($builder);
	}
}

namespace App\GraphQL\Definition;

class PostDefinition extends EloquentDefinition {
	// ...

	/**
	 * {@inheritDoc}
	 *
	 * @return array
	 */
	public function getPipes(): array {
		return array_merge_recursive(parent::getPipes(), [
			'list' => [\App\GraphQL\Pipe\OnlyAuthored::class],
		]);
	}
	
	// ...
}

namespace App/GraphQL/Pipe;

use Closure;
use Illuminate\Database\Eloquent\Builder;
use GraphQL\Type\Definition\Type;
use StudioNet\GraphQL\Support\Pipe\Argumentable;
use StudioNet\GraphQL\Support\Definition\Definition;

class FilterableGroups implements Argumentable {
	/**
	 * returns only given groups
	 *
	 * @param  Builder $builder
	 * @param  Closure $next
	 * @param  array $opts
	 * @return \Illuminate\Database\Eloquent\Model
	 */
	public function handle(Builder $builder, Closure $next, array $opts) {
		if (array_get($opts, ['args.group_ids', false])) {
			$builder->whereIn('group_id', $opts['args']['group_ids']);
		}

		return $next($builder);
	}

	/**
	 * @implements
	 *
	 * @param  Definition $definition
	 * @return array
	 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
	 */
	public function getArguments(Definition $definition): array {
		return [
			'groups_id' => [
				'type' => Type::json(),
				'description' => 'Filtering by group IDs'
			]
		];
	}
}

	public function getFilterable() {
		return [
			// Simple equality check (or "in" if value is an array). Type is Type::json()
			'id'       => new EqualsOrContainsFilter(),
			
			// Customized filter. Type is Type::json()
			"nameLike" => function($builder, $value) {
				return $builder->whereRaw('name like ?', $value);
			},
			
			// type is Type::string()
			"anotherFilter" => [
				"type" => Type::string(),
				"resolver" => function($builder, $value) {
					return $builder->whereRaw('anotherFilter like ?', $value);				
				}
			],
			
			// type is what is returned from `ComplexFilter::getType()`.
			// This is the preffered way to define filters, as it keeps definitions code clean
			"complexFilter" => new ComplexFilter(),
			
			// type in array will be overriden by what is returned from `ComplexFilter::getType()`.
			// this kind of difinition is not clear, but is implemented for backward compatibilities. Please don't use it
			"complexFilter2" => [
				"type" => Type::int(),
				"resolver" => new ComplexFilter()
			],
		];
	}

	use Illuminate\Database\Eloquent\Model;

	/* ... */

	public function getMutable() {
		return [
			'id' => Type::id(),
			'name' => Type::string(),
			// ...
			// Define a custom input field, which will uppercase the value
			'name_uppercase' => Type::string(),
		];
	}

	/* ... */

	/**
	 * Custom input field for name_uppercase
	 *
	 * @param Model $model
	 * @param string $value
	 */
	public function inputNameUppercaseField(Model $model, $value) {
		$model->name = mb_strtoupper($value);
	}

	/**
	 * Custom input field for name_uppercase
	 *
	 * @param Model $model
	 * @param string $value
	 */
	public function inputNameUppercaseField(Model $model, $value) {
		$model->name = mb_strtoupper($value);

		return [
			'saved' => function() use ($model, $value) {
				// Executed after save
			}
		];
	}
bash
php artisan vendor:publish --provider="StudioNet\GraphQL\ServiceProvider"
bash
$> ./vendor/bin/phpmd src text phpmd.xml
$> ./vendor/bin/phpmd tests text phpmd.xml
$> ./vendor/bin/phpstan analyse --autoload-file=_ide_helper.php --level 1 src
$> ./vendor/bin/php-cs-fixer fix