Weave Code
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

Lara Asp Graphql Laravel Package

lastdragon-ru/lara-asp-graphql

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require lastdragon-ru/lara-asp-graphql
    

    Ensure your composer.json meets the PHP/Laravel version requirements.

  2. Publish Config (Optional):

    php artisan vendor:publish --provider="LastDragon\LaraAspGraphQL\LaraAspGraphQLServiceProvider" --tag="config"
    

    Modify config/lara-asp-graphql.php if needed (e.g., custom operators, default behavior).

  3. First Use Case: Define a GraphQL type with @searchBy and @sortBy directives. Example:

    type User @model {
      id: ID! @searchBy
      name: String @searchBy
      email: String @searchBy(operators: ["=", "!=", "contains"])
      posts: [Post!]! @searchBy(relation: "posts")
    }
    

    Query with filtering:

    query {
      users @searchBy(where: { email: { _eq: "test@example.com" } }) {
        id
        name
      }
    }
    

Implementation Patterns

Core Workflows

  1. Searching with @searchBy:

    • Basic Conditions: Use _eq, _neq, _gt, _lt, etc. for field comparisons.
      users @searchBy(where: { age: { _gt: 25 } })
      
    • Relational Queries: Filter by related models.
      posts @searchBy(where: { author: { _eq: { id: 1 } } })
      
    • Nested Conditions: Combine with and/or/not.
      users @searchBy(where: {
        and: [
          { name: { _contains: "John" } },
          { not: { active: { _eq: false } } }
        ]
      })
      
    • Enums/Custom Operators: Define in config or schema.
      type UserStatus @enum {
        ACTIVE
        INACTIVE
      }
      # Query:
      users @searchBy(where: { status: { _eq: ACTIVE } })
      
  2. Sorting with @sortBy:

    • Sort by fields or relations.
      users @sortBy(orderBy: [{ field: "name", direction: ASC }])
      
    • Relation-based sorting:
      posts @sortBy(orderBy: [{ field: "author.name", direction: DESC }])
      
  3. Streaming with @stream:

    • Paginate or stream large datasets.
      users @stream(first: 10) {
        id
        name
      }
      

Integration Tips

  • Lighthouse Schema: Extend existing Lighthouse types without breaking changes. Use @searchBy on existing fields or add new ones.

    type User @model {
      # Existing fields...
      createdAt: DateTime @searchBy(format: "Y-m-d")
    }
    
  • Dynamic Directives: Use resolve functions to dynamically apply directives based on runtime logic (e.g., role-based filtering).

    type Query {
      adminUsers: [User!]! @searchBy(where: { role: { _eq: "admin" } })
    }
    
  • Performance:

    • Indexing: Ensure database columns used in @searchBy are indexed.
    • Selective Loading: Use @field or @resolve to avoid N+1 queries with relations.
      type User @model {
        posts: [Post!]! @field(resolve: "postsWithPagination")
      }
      

Gotchas and Tips

Pitfalls

  1. Type Mismatches:

    • @searchBy enforces strict typing. Ensure query operators match field types (e.g., _contains for String, not Int).
    • Fix: Use Mixed type sparingly; prefer explicit types like String! or Int!.
  2. Relation Ambiguity:

    • Nested relations (e.g., author.posts.title) may fail if intermediate relations lack proper @searchBy definitions.
    • Fix: Define @searchBy on all intermediate relation fields or use dot notation carefully.
  3. Operator Overload:

    • Custom operators (e.g., _startsWith) must be registered in the config or schema. Undefined operators throw errors.
    • Fix: Extend config/lara-asp-graphql.php:
      'operators' => [
        'string' => [
          'startsWith' => 'like',
          'endsWith'   => 'like',
        ],
      ],
      
  4. Pagination Conflicts:

    • @stream may conflict with Lighthouse’s default pagination. Ensure first/after args are consistent.
    • Fix: Disable default pagination in config/lighthouse.php if using @stream.
  5. Case Sensitivity:

    • Database collations affect _contains/_startsWith. MySQL’s utf8mb4_general_ci is case-insensitive; utf8mb4_bin is strict.
    • Fix: Use _icontains (if supported) or standardize case in queries.

Debugging

  • Query Validation Errors: Use GraphQL Playground/Altair to inspect errors. Enable Lighthouse’s debug mode:

    'debug' => env('APP_DEBUG', false),
    

    in config/lighthouse.php.

  • SQL Logging: Enable Laravel’s query logging to verify generated SQL:

    DB::enableQueryLog();
    // Execute query...
    dd(DB::getQueryLog());
    
  • Directive Resolution: Override directive resolvers in a custom service provider:

    public function boot()
    {
        $this->app->extend('lighthouse.directives.searchBy', function ($resolver) {
            return new CustomSearchByResolver($resolver);
        });
    }
    

Extension Points

  1. Custom Operators: Extend the package by adding operators in config/lara-asp-graphql.php:

    'operators' => [
        'string' => [
            'customOp' => 'raw', // Uses raw SQL
        ],
        'callback' => [
            'isActive' => function ($query, $value) {
                return $query->where('status', 'active')->orWhere('suspended_at', '>', now());
            },
        ],
    ],
    
  2. Custom Directives: Create reusable directives by extending the base classes:

    namespace App\GraphQL\Directives;
    
    use LastDragon\LaraAspGraphQL\Directives\BaseDirective;
    
    class CustomSearch extends BaseDirective
    {
        protected function resolve(): void
        {
            // Custom logic
        }
    }
    

    Register in config/lara-asp-graphql.php:

    'directives' => [
        'customSearch' => \App\GraphQL\Directives\CustomSearch::class,
    ],
    
  3. Relation Handling: Override relation resolution for complex cases:

    type User @model {
      orders: [Order!]! @searchBy(
        relation: "orders",
        resolver: "customOrderResolver"
      )
    }
    

    Define resolver in a Lighthouse resolver class.

  4. Performance Hooks: Use Laravel’s model events to preload relations before @searchBy executes:

    User::addGlobalScope('preloadRelations', function (Builder $builder) {
        $builder->with(['posts.author']);
    });
    

Pro Tips

  • Reusable Fragments: Define GraphQL fragments for common @searchBy queries:

    fragment UserFilter on User @searchBy {
       id: ID @searchBy(operators: ["=", "!="])
       name: String @searchBy(operators: ["_contains"])
     }
    
  • API Versioning: Use @deprecated alongside @searchBy to phase out old fields:

    field oldName: String @searchBy @deprecated(reason: "Use 'name' instead")
    
  • Testing: Mock directives in PHPUnit:

    $this->app->instance('lighthouse.directives.searchBy', $mockResolver);
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle