Mutations
Creating a Mutation
To create a mutation, you can use Lighthouse's make command
$ php artisan lighthouse:mutation CreateUserMutation
Mutation Class
You can add rules to your arguments just as you would when validating in a Controller.
namespace App\Http\GraphQL\Mutations;
use GraphQL\Type\Definition\Type;
use Nuwave\Lighthouse\Support\Definition\GraphQLMutation;
class CreateUserMutation extends GraphQLMutation
{
/**
* Attributes of mutation.
*
* @var array
*/
protected $attributes = [
'name' => 'createUser'
];
/**
* Type that mutation returns.
*
* @return ObjectType
*/
public function type()
{
return GraphQL::type('user');
}
/**
* Available arguments on mutation.
*
* @return array
*/
public function args()
{
return [
'name' => [
'type' => Type::nonNull(Type::string()),
'description' => 'Name for the user.',
'rules' => ['required', 'min:2'],
],
'email' => [
'type' => Type::nonNull(Type::string()),
'description' => 'Email address for the user.',
'rules' => ['required', 'email'],
],
];
}
/**
* Resolve the mutation.
*
* @param mixed $root
* @param array $args
* @return mixed
*/
public function resolve($root, array $args)
{
return \App\User::create($args);
}
}
Creating a Relay Mutation
If you are using Relay to consume your GraphQL server, you can use the --relay
option to create a Relay compliant mutation.
$ php artisan lighthouse:mutation CreateUserMutation --relay
Relay Mutation Class
namespace App\Http\GraphQL\Mutations;
use GraphQL;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use Nuwave\Lighthouse\Support\Definition\GraphQLMutation;
use Nuwave\Lighthouse\Support\Interfaces\RelayMutation;
class CreateUserMutation extends GraphQLMutation implements RelayMutation
{
/**
* Attributes of mutation.
*
* @var array
*/
protected $attributes = [
'name' => 'createUser'
];
/**
* Available arguments on mutation.
*
* @return array
*/
public function args()
{
return [
'name' => [
'type' => Type::nonNull(Type::string()),
'description' => 'Name for the user.',
'rules' => ['required', 'min:2'],
],
'email' => [
'type' => Type::nonNull(Type::string()),
'description' => 'Email address for the user.',
'rules' => ['required', 'email'],
],
];
}
/**
* List of output fields.
*
* @return array
*/
public function outputFields()
{
return [
'user' => [
'type' => GraphQL::type('user'),
'resolve' => function ($payload) {
return $payload['user'];
}
],
];
}
/**
* Resolve the mutation.
*
* @param array $args
* @param mixed $context
* @param ResolveInfo $info
* @return mixed
*/
public function mutateAndGetPayload(array $args, $context, ResolveInfo $info)
{
$user = \App\User::create(array_merge($args, [
'created_by' => auth()->user()->id,
]));
// You don't have to return an array as the payload, this is just an example.
return [
'user' => $user,
'creator' => auth()->user(),
];
}
}