Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Graphql Laravel Package

cfpinto/graphql

Laravel package to add a GraphQL API to your app, offering schema setup, query/mutation handling, and integration with Laravel’s routing and services so you can expose application data through GraphQL with minimal boilerplate.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cfpinto/graphql
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        CFPinto\GraphQL\GraphQLServiceProvider::class,
    ],
    
  2. Basic Query Builder Import the GraphQL facade:

    use CFPinto\GraphQL\Facades\GraphQL;
    

    Construct a simple query:

    $query = GraphQL::query('users')
        ->select(['id', 'name', 'email'])
        ->first();
    
  3. First Use Case: Fetching a Single Resource

    $user = GraphQL::query('users')
        ->where('id', 1)
        ->first();
    

Implementation Patterns

Query Building Workflows

  1. CRUD Operations

    • Create:
      $created = GraphQL::mutation('createUser')
          ->setVariables(['name' => 'John', 'email' => '[email protected]'])
          ->execute();
      
    • Read:
      $users = GraphQL::query('users')
          ->paginate(10)
          ->get();
      
    • Update:
      $updated = GraphQL::mutation('updateUser')
          ->where('id', 1)
          ->setVariables(['name' => 'Updated Name'])
          ->execute();
      
    • Delete:
      $deleted = GraphQL::mutation('deleteUser')
          ->where('id', 1)
          ->execute();
      
  2. Nested Relationships

    $posts = GraphQL::query('posts')
        ->with(['author' => ['name', 'email']])
        ->get();
    
  3. Conditional Queries

    if ($activeOnly) {
        $query = GraphQL::query('users')->where('active', true);
    }
    

Integration with Laravel

  • Eloquent Integration Use the fromModel() helper to map queries to Eloquent models:

    $query = GraphQL::query()->fromModel(User::class)->select(['id', 'name']);
    
  • API Resource Transformation Convert results to API resources:

    $users = GraphQL::query('users')->get()->transform(new UserResource());
    
  • Middleware for Authentication Wrap queries in middleware for authorization:

    $query = GraphQL::query('adminDashboard')->middleware('can:view-admin');
    

Gotchas and Tips

Common Pitfalls

  1. Schema Mismatch

    • Ensure your GraphQL schema matches the query structure. Mismatched fields will throw errors.
    • Debug Tip: Use GraphQL::debug(true) to log raw queries and responses.
  2. Variable Injection Risks

    • Avoid dynamically setting variables from untrusted sources (e.g., user input). Sanitize or validate variables:
      $variables = ['id' => (int) request('id')];
      GraphQL::mutation('updateUser')->setVariables($variables)->execute();
      
  3. Pagination Quirks

    • The paginate() method assumes the GraphQL endpoint returns a pageInfo object. Customize with:
      GraphQL::query('users')->paginate(10, 'customCursorField');
      

Debugging

  • Enable Debug Mode

    GraphQL::debug(true); // Logs queries and responses to Laravel logs
    
  • Inspect Raw Queries Use GraphQL::getQuery() to see the constructed query string before execution:

    $queryString = GraphQL::query('users')->select(['id'])->getQuery();
    

Extension Points

  1. Custom Query Builders Extend the base builder for domain-specific logic:

    class UserQueryBuilder extends \CFPinto\GraphQL\QueryBuilder
    {
        public function activeOnly()
        {
            return $this->where('active', true);
        }
    }
    

    Register it in the service provider:

    GraphQL::extend('users', UserQueryBuilder::class);
    
  2. Response Transformers Override default response handling:

    GraphQL::transformer(function ($response) {
        return collect($response)->map(fn ($item) => [
            'id' => $item['id'],
            'full_name' => $item['first_name'] . ' ' . $item['last_name']
        ]);
    });
    
  3. Error Handling Customize error responses globally:

    GraphQL::onError(function (\Exception $e) {
        return response()->json(['error' => $e->getMessage()], 500);
    });
    

Configuration Quirks

  • Default Headers Set default headers (e.g., for authentication) in config/graphql.php:

    'headers' => [
        'Authorization' => 'Bearer ' . auth()->token(),
    ],
    
  • Endpoint Overrides Override the default endpoint per query:

    GraphQL::query('users')->endpoint('https://custom-api.com/graphql');
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log