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

Zatona Eg Api Laravel Package

zatona-eg/zatona-eg-api

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First API Endpoint

  1. Install the Package

    composer require zatona-eg/zatona-eg-api
    php artisan zatona-eg-api:install
    
    • This auto-configures API Platform, GraphQL, and REST endpoints for Bagisto v2.3.8+.
  2. Access the API

    • REST Docs: Visit /api/shop/docs (shop) or /api/admin/docs (admin) for Swagger/OpenAPI docs.
    • GraphQL Playground: Navigate to /api/graphiql (shop) or /api/admin/graphiql (admin).
  3. First Use Case: Fetch Products

    • REST: GET /api/shop/products (returns paginated product list).
    • GraphQL:
      query {
        products {
          id
          name
          slug
        }
      }
      

Key Files to Explore

  • API Resources: app/Http/Resources/ (customize REST responses).
  • GraphQL Schema: config/graphql.php (extend types/resolvers).
  • Middleware: app/Http/Middleware/ (auth/validation layers).

Implementation Patterns

1. REST API Workflows

  • Resource Customization: Use php artisan make:resource to extend default resources (e.g., ProductResource). Example:
    // app/Http/Resources/ProductResource.php
    public function toArray($request, Product $product) {
        return [
            'id' => $product->id,
            'name' => $product->name,
            'custom_field' => $product->customField, // Add custom attributes
        ];
    }
    
  • Filtering/Sorting: Leverage API Platform’s built-in filters (e.g., ?filter[name][contains]=phone). Override in Product entity:
    #[ApiFilter(SearchFilter::class, properties: ['name', 'description'])]
    class Product extends Model {}
    

2. GraphQL Integration

  • Extend Schema: Add custom types/resolvers in config/graphql.php:
    'types' => [
        'Product' => [
            'fields' => [
                'customField' => [
                    'type' => 'String',
                    'resolve' => fn ($product) => $product->customField,
                ],
            ],
        ],
    ],
    
  • Mutations: Create resolvers for write operations (e.g., createProduct):
    // app/GraphQL/Mutations/CreateProduct.php
    class CreateProduct implements Mutation {
        public function resolve() {
            return Product::create($this->args['input']);
        }
    }
    

3. Authentication

  • Token-Based Auth: Use php artisan make:auth to generate API tokens for clients. Protect routes in routes/api.php:
    Route::middleware('auth:api')->group(function () {
        Route::apiResource('orders', OrderController::class);
    });
    
  • Admin/Shop Context: Prefix routes with /api/shop/ (public) or /api/admin/ (admin-only).

4. Testing APIs

  • REST: Use Laravel’s Http tests:
    $response = $this->getJson('/api/shop/products');
    $response->assertStatus(200);
    
  • GraphQL: Test with graphql helper:
    $result = $this->graphql('query { products { id name } }');
    $result->assertNoErrors();
    

Gotchas and Tips

Pitfalls

  1. Version Mismatch:

    • The package is hard-pinned to Bagisto v2.3.8. Upgrading Bagisto may break APIs.
    • Fix: Check composer.json for bagisto/bagisto version conflicts.
  2. GraphQL Caching:

    • Schema caching (php artisan graphql:cache) can cause issues if resolvers change.
    • Tip: Clear cache after schema updates:
      php artisan graphql:clear-cache
      
  3. REST vs. GraphQL Duplication:

    • Avoid duplicating logic between REST resources and GraphQL resolvers.
    • Tip: Use shared services (e.g., ProductService) for business logic.
  4. Pagination Limits:

    • Default pagination (e.g., 15 items/page) may not suit all clients.
    • Fix: Override in ProductResource:
      public function toArray($request) {
          return $this->collection->through(fn ($product) => [...])->paginate(50);
      }
      

Debugging Tips

  • REST Errors: Check storage/logs/laravel.log for API Platform errors (e.g., validation failures). Enable debug mode in config/api_platform.php:

    'debug' => env('APP_DEBUG', true),
    
  • GraphQL Errors: Use the GraphQL Playground to inspect errors. For resolver issues, add:

    try {
        return $this->resolve();
    } catch (\Exception $e) {
        throw new GraphQLException($e->getMessage());
    }
    

Extension Points

  1. Custom API Platform State Providers: Extend ApiStateProvider to modify API responses globally:

    // app/Providers/ApiStateProvider.php
    public function getState($resourceClass, array $collection = []): array {
        return array_merge(parent::getState($resourceClass, $collection), [
            'custom_metadata' => 'value',
        ]);
    }
    
  2. Webhook Integration: Use api-platform/core events to trigger actions (e.g., on product creation):

    // app/Providers/EventServiceProvider.php
    public function boot() {
        event(new ProductCreated($product));
    }
    
  3. Performance:

    • REST: Use #[ApiResource(itemOperations: ['get'])] to disable unnecessary endpoints.
    • GraphQL: Batch loading with #[ApiResource(useResultPager: true)].

Configuration Quirks

  • CORS: Ensure config/cors.php allows API domains:

    'paths' => ['api/*', 'graphiql'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'], // Restrict in production!
    
  • Rate Limiting: Enable in app/Http/Kernel.php:

    \Illuminate\Cache\RateLimiting\Limit::perMinute(60)->by($this->resolveRequest()->ip());
    
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style