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

Laravel Plugin Laravel Package

saloonphp/laravel-plugin

Laravel plugin for Saloon that brings tight framework integration: service container bindings, config publishing, artisan tooling, and convenient HTTP client setup for building and managing API connectors and requests cleanly within Laravel apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation:

    composer require saloonphp/laravel-plugin
    

    Publish the configuration:

    php artisan vendor:publish --provider="Saloon\Laravel\PluginServiceProvider"
    
  2. Generate a Connector:

    php artisan saloon:connector Stripe
    

    This creates a StripeConnector class in app/Integrations/Connectors/StripeConnector.php.

  3. Define a Request:

    php artisan saloon:request Stripe GetPaymentMethods
    

    Generates a request class in app/Integrations/Requests/Stripe/GetPaymentMethodsRequest.php.

  4. Use the Request:

    use App\Integrations\Requests\Stripe\GetPaymentMethodsRequest;
    
    $response = GetPaymentMethodsRequest::send();
    
  5. First Use Case: Quickly scaffold a fully typed API client for Stripe (or any API) with authentication, retries, and response validation built-in.


Where to Look First

  • Documentation: Start with the SaloonPHP docs and the Laravel Plugin README.
  • Configuration: Check config/saloon.php for integration paths, default connectors, and middleware settings.
  • Artisan Commands: Explore saloon:list, saloon:request, and saloon:connector for scaffolding.
  • Examples: Review the tests/ directory in the package for integration patterns.

Implementation Patterns

Core Workflows

1. Scaffolding API Clients

  • Use saloon:connector to create a base connector (e.g., StripeConnector).
  • Define authentication in the connector (e.g., API keys, OAuth tokens).
  • Generate requests with saloon:request and specify HTTP methods (GET, POST, etc.).
// app/Integrations/Connectors/StripeConnector.php
public function resolveBaseUrl(): string
{
    return 'https://api.stripe.com/v1';
}

public function defaultHeaders(): array
{
    return [
        'Authorization' => 'Bearer ' . $this->apiKey,
    ];
}

2. Request-Response Contracts

  • Define input/output contracts for requests to enforce validation.
  • Use Saloon’s shouldBeValid() for automatic response validation.
// app/Integrations/Requests/Stripe/GetPaymentMethodsRequest.php
public function resolveEndpoint(): string
{
    return '/payment_methods';
}

public function shouldBeValid(): array
{
    return [
        'data' => [
            '*' => [
                'id' => 'required|string',
                'type' => 'required|string',
            ],
        ],
    ];
}

3. Middleware Integration

  • Register middleware globally in config/saloon.php or per-connector.
  • Use built-in middleware (e.g., RetryMiddleware, JsonParseMiddleware) or create custom ones.
// config/saloon.php
'middleware' => [
    \Saloon\Http\Middleware\JsonParseMiddleware::class,
    \Saloon\Http\Middleware\RetryMiddleware::class,
],

4. Testing with Mocks

  • Use Saloon::fake() to mock API responses in tests.
  • Simulate failures or delays for edge-case testing.
// tests/Feature/StripeIntegrationTest.php
public function test_get_payment_methods()
{
    Saloon::fake([
        GetPaymentMethodsRequest::class => Http::response([
            'data' => [['id' => 'pm_123', 'type' => 'card']],
        ]),
    ]);

    $response = GetPaymentMethodsRequest::send();
    $this->assertEquals('pm_123', $response->data[0]['id']);
}

5. Observability

  • Integrate with Laravel Telescope or Pulse for monitoring API calls.
  • Log requests/responses using Saloon’s Observers or middleware.
// app/Providers/AppServiceProvider.php
public function boot()
{
    Saloon::observe(function ($request, $response) {
        \Log::info('API Call', [
            'request' => $request->toArray(),
            'response' => $response->toArray(),
        ]);
    });
}

Integration Tips

Laravel Service Container

  • Bind connectors/requests to the container for dependency injection:
    $this->app->bind(
        StripeConnector::class,
        fn ($app) => new StripeConnector($app['config']['services.stripe.key'])
    );
    

Queues and Jobs

  • Dispatch requests as jobs for async processing:
    GetPaymentMethodsRequest::dispatch();
    

Events

  • Trigger events on request success/failure:
    public function shouldBeValid(): array
    {
        return [
            'data' => [...],
        ];
    }
    
    public function onSuccess($response)
    {
        event(new PaymentMethodsFetched($response));
    }
    

API Versioning

  • Use connectors to manage multiple API versions:
    // StripeConnector.php
    public function resolveBaseUrl(): string
    {
        return config('services.stripe.api_version') === 'v2'
            ? 'https://api.stripe.com/v2'
            : 'https://api.stripe.com/v1';
    }
    

Gotchas and Tips

Pitfalls

  1. Integration Path Configuration:

    • If integrations_path in config/saloon.php is misconfigured, generated classes may appear in the wrong directory.
    • Fix: Ensure the path points to app/Integrations (default) or adjust accordingly.
      'integrations_path' => app_path('Integrations'),
      
  2. Middleware Registration:

    • Middleware like NightwatchMiddleware (for monitoring) may register multiple times if not guarded.
    • Fix: Use the shouldRegister() method in middleware to avoid duplicates.
  3. Sensitive Data Handling:

    • Hardcoding API keys in connectors violates security best practices.
    • Fix: Use Laravel’s config/services.php or environment variables:
      public function defaultHeaders(): array
      {
          return [
              'Authorization' => 'Bearer ' . config('services.stripe.key'),
          ];
      }
      
  4. Deprecated Methods:

    • Saloon::fake() with MockClient is deprecated in v3+. Use the global mock client instead.
    • Fix: Update tests to use:
      Saloon::fake([GetPaymentMethodsRequest::class => Http::response(...)]);
      
  5. PHP 8.5+ Compatibility:

    • Some older middleware or connectors may need updates for PHP 8.5’s strict typing.
    • Fix: Check for @php version directives or update dependencies.

Debugging Tips

  1. Enable Verbose Logging:

    • Set SALOON_DEBUG=true in .env to log raw requests/responses.
    • Use Telescope or Pulse for deeper inspection.
  2. Contract Validation Errors:

    • If shouldBeValid() fails, check the response structure and adjust the validation rules.
    • Tip: Use dd($response->toArray()) to inspect the raw response.
  3. Network Issues:

    • Saloon retries failed requests by default. To disable:
      public function resolveRetryMiddleware(): array
      {
          return [];
      }
      
  4. IDE Support:

    • The ide.json file provides hints for PHPStorm/VSCode. Ensure it’s loaded in your IDE.

Extension Points

  1. Custom Middleware:

    • Extend Saloon\Http\Concerns\HasMiddleware to add logic (e.g., request signing, headers).
    • Example: Add a SignatureMiddleware for HMAC-authenticated APIs.
  2. Dynamic Endpoints:

    • Override resolveEndpoint() dynamically based on request data:
      public function resolveEndpoint(): string
      {
          return "/users/{$this->userId}";
      }
      
  3. Webhook Handling:

    • Use Saloon to validate and process incoming webhooks:
      public function shouldBeValid(): array
      {
          return [
              'event' => 'required|string',
              'data' => 'required|array',
          ];
      }
      
  4. Testing Utilities:

    • Extend SaloonTestCase for reusable test setups:
      use Saloon\Testing\SaloonTestCase;
      
      class StripeTest extends SaloonTestCase
      {
          protected function setUp(): void
          {
              Saloon::fake([...]);
          }
      }
      
  5. Laravel Boost Integration:

    • Use saloon-development skill to enforce
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