To implement validation with GraphQL and the Webonyx package in Laravel, you can use Laravel's built-in validation system. Here's an example of how to do this:
- Create a new validation rule class that extends Laravel's
Ruleclass. This class will contain the validation logic for your GraphQL input.
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class ExampleValidationRule implements Rule
{
public function passes($attribute, $value)
{
// Perform validation logic here
return true; // Return true if validation passes, false otherwise
}
public function message()
{
return 'The validation error message';
}
}
- In your GraphQL mutation resolver, use Laravel's
Validatorclass to validate the input using your custom validation rule.
<?php
namespace App\GraphQL\Mutations;
use App\Rules\ExampleValidationRule;
use Illuminate\Support\Facades\Validator;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
class ExampleMutation
{
public function __invoke($rootValue, array $args, GraphQLContext $context)
{
$validator = Validator::make($args, [
'input_field' => [new ExampleValidationRule],
]);
if ($validator->fails()) {
throw new \Exception($validator->errors()->first());
}
// Perform mutation logic here
return ['success' => true];
}
}
-
To use GraphiQL to validate your queries and mutations, you can use the GraphiQL IDE that comes with the Laravel Lighthouse package. You can access it by visiting
/graphql-playgroundin your browser. -
To test your queries, mutations, and subscriptions, you can use the
graphql-phptest framework that comes with the Webonyx package. Here's an example of how to use it:
<?php
namespace Tests\GraphQL;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Nuwave\Lighthouse\Testing\MakesGraphQLRequests;
class ExampleTest extends TestCase
{
use RefreshDatabase, MakesGraphQLRequests;
public function testExampleQuery()
{
$this->graphQL('
query {
exampleQuery {
id
name
}
}
')->assertJson([
'data' => [
'exampleQuery' => [
'id' => 1,
'name' => 'Example',
],
],
]);
}
public function testExampleMutation()
{
$this->graphQL('
mutation {
exampleMutation(input: {
input_field: "example_value"
}) {
success
}
}
')->assertJson([
'data' => [
'exampleMutation' => [
'success' => true,
],
],
]);
}
}
This test will send a GraphQL query to your application and assert that the response matches the expected JSON structure. You can use this framework to test all of your GraphQL queries, mutations, and subscriptions.