Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I customize the resolver middleware for different queries in Laravel 11
    Laravel 11 GraphQL rebing/graphql-laravel resolver middleware customize middleware Laravel API middleware configuration


Can I customize the resolver middleware for different queries in Laravel 11


Yes, you can customize the resolver middleware for different queries in Laravel 11 when using the `rebing/graphql-laravel` package. Here's how you can do it:

1. Define the resolver middleware: Create a resolver middleware class that implements the `Rebing\GraphQL\Support\ResolverMiddleware` interface. This middleware will be executed before the resolver function is called.

php
namespace App\GraphQL\Middleware;

use Closure;
use Rebing\GraphQL\Support\ResolverMiddleware;

class LogResolverMiddleware implements ResolverMiddleware
{
    public function handle($root, $args, $context, $info, Closure $next)
    {
        // Perform some logic before the resolver is executed
        logger()->info('Resolver called', ['root' => $root, 'args' => $args]);

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

2. Configure the resolver middleware: In your `config/graphql.php` file, you can configure the resolver middleware for specific queries or mutations.

php
'schemas' => [
    'default' => [
        'query' => [
            'users' => [
                'middleware' => [
                    \App\GraphQL\Middleware\LogResolverMiddleware::class,
                ],
            ],
        ],
        'mutation' => [
            'createUser' => [
                'middleware' => [
                    \App\GraphQL\Middleware\LogResolverMiddleware::class,
                ],
            ],
        ],
    ],
],

In this example, the `LogResolverMiddleware` will be applied to the `users` query and the `createUser` mutation. You can define different middleware for other queries and mutations as needed.

3. Apply the middleware globally: If you want to apply the resolver middleware globally, you can configure it in the `graphql.resolver_middleware` option in the `config/graphql.php` file.

php
'resolver_middleware' => [
    \App\GraphQL\Middleware\LogResolverMiddleware::class,
],

This will apply the `LogResolverMiddleware` to all resolvers in your GraphQL API.

By using this approach, you can easily customize the resolver middleware for specific queries and mutations in your Laravel 11 GraphQL API, allowing you to add custom logic or perform additional checks before the resolver is executed.

Citations:
[1] https://benjamincrozat.com/customize-middleware-laravel-11
[2] https://github.com/rebing/graphql-laravel
[3] https://aarrsolprivatelimited.com/laravel-11-features-for-web-app/
[4] https://larachamp.com/how-to-configure-middleware-in-laravel-11/
[5] https://laravel.com/docs/11.x/middleware