Custom Fields
Creating a Custom Field
To create a custom field, you can use Lighthouse's make command
$ php artisan lighthouse:field AvatarField
Custom Field Class
namespace App\Http\GraphQL\Fields;
use GraphQL;
use GraphQL\Type\Definition\Type;
use Nuwave\Lighthouse\Support\Definition\GraphQLField;
class Avatar extends GraphQLField
{
/**
* Field attributes.
*
* @var array
*/
protected $attributes = [
'description' => 'User avatar.',
];
/**
* The return type of the field.
*
* @return Type
*/
public function type()
{
return Type::string();
}
/**
* Available field arguments.
*
* @return array
*/
public function args()
{
return [
'size' => [
'type' => Type::nonNull(Type::int()),
'description' => 'Size (in pixels) of avatar.',
]
];
}
/**
* Resolve the field.
*
* @param mixed $root
* @param array $args
* @return mixed
*/
public function resolve($root, array $args)
{
return $root->avatar($args['size']);
}
}
Using a Custom Field in a Type
// ...
use App\Http\GraphQL\Fields\Avatar;
class UserType extends GraphQLType implements RelayType
{
// ...
/**
* Type fields.
*
* @return array
*/
public function fields()
{
return [
// ...
'avatar' => Avatar::field(),
];
}
}