Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I set up GraphQL execution middleware for a specific schema in Laravel 11
    Laravel 11 GraphQL execution middleware schema configuration Laravel GraphQL middleware GraphQL middleware setup


How do I set up GraphQL execution middleware for a specific schema in Laravel 11


To set up GraphQL execution middleware for a specific schema in Laravel 11, you can follow these steps:

1. Define your GraphQL execution middleware class. This middleware will be executed during the processing of a GraphQL request. For example:

php
namespace App\GraphQL\Middleware;

use Closure;
use Nuwave\Lighthouse\Schema\Context;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

class LogExecutionMiddleware
{
    public function handle($root, array $args, Context $context, ResolveInfo $resolveInfo, Closure $next)
    {
        // Perform some logic before the execution
        logger()->info('GraphQL query executed', ['query' => $resolveInfo->getFieldName()]);

        // Call the next middleware or the resolver
        return $next($root, $args, $context, $resolveInfo);
    }
}

2. Configure the execution middleware for the specific schema in your `config/graphql.php` file:

php
'schemas' => [
    'default' => [
        'execution_middleware' => [
            \App\GraphQL\Middleware\LogExecutionMiddleware::class,
        ],
    ],
],

In this example, the `LogExecutionMiddleware` will be applied to the `default` schema during GraphQL request execution.

3. If you have multiple schemas, you can configure the middleware for each schema individually:

php
'schemas' => [
    'default' => [
        'execution_middleware' => [
            \App\GraphQL\Middleware\LogExecutionMiddleware::class,
        ],
    ],
    'another_schema' => [
        'execution_middleware' => [
            \App\GraphQL\Middleware\AnotherExecutionMiddleware::class,
        ],
    ],
],

By following these steps, you can set up GraphQL execution middleware for a specific schema in your Laravel 11 application. The middleware will be executed during the processing of GraphQL requests for that schema, allowing you to add custom logic or perform additional checks before the actual resolvers are called.

Citations:
[1] https://www.turing.com/kb/setting-a-graphql-server-using-laravel
[2] https://github.com/rebing/graphql-laravel
[3] https://www.toptal.com/graphql/laravel-graphql-server-tutorial
[4] https://magecomp.com/blog/create-user-register-login-graphql-api-laravel/
[5] https://developer.okta.com/blog/2021/12/22/graphql-laravel