Types
Creating a Type
To create a type, you can use Lighthouse's make command
$ php artisan lighthouse:type UserType
Type Class
A type class consists of attributes (name and description) along with it's defined fields.
namespace App\Http\GraphQL\Types;
use GraphQL;
use GraphQL\Type\Definition\Type;
use Nuwave\Lighthouse\Support\Definition\GraphQLType;
class UserType extends GraphQLType
{
/**
* Attributes of type.
*
* @var array
*/
protected $attributes = [
'name' => 'User',
'description' => 'Application user.'
];
/**
* Type fields.
*
* @return array
*/
public function fields()
{
return [
'id' => [
'type' => Type::id(),
'description' => 'ID of the user.',
],
'name' => [
'type' => Type::string(),
'description' => 'Full name of the user.',
],
'email' => [
'type' => Type::string(),
'description' => 'Email address of the user.'
],
];
}
}
Creating a Relay Type
If you intend to utilize your types with Relay, you can use the --relay
option with the make command.
$ php artisan lighthouse:type --relay
Relay Type Class
The primary difference with a relay type is that it uses the Node Interface, which allows Relay (or any other consumer of the GraphQL server) to reference the type by it's unique id.
namespace App\Http\GraphQL\Types;
use GraphQL;
use GraphQL\Type\Definition\Type;
use Nuwave\Lighthouse\Support\Definition\GraphQLType;
use Nuwave\Lighthouse\Support\Interfaces\RelayType;
class UserType extends GraphQLType implements RelayType
{
/**
* Attributes of type.
*
* @var array
*/
protected $attributes = [
'name' => 'User',
'description' => 'Application user.'
];
/**
* Get model by id.
*
* Note: When the root 'node' query is called, this method
* will be used to resolve the type by providing the id.
*
* @param mixed $id
* @return mixed
*/
public function resolveById($id)
{
return \App\User::find($id);
}
/**
* Type fields.
*
* @return array
*/
public function fields()
{
return [
'id' => [
'type' => Type::id(),
'description' => 'ID of the user.',
],
'name' => [
'type' => Type::string(),
'description' => 'Full name of the user.',
],
'email' => [
'type' => Type::string(),
'description' => 'Email address of the user.'
],
];
}
}