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

Curl Laravel Package

ixudra/curl

ixudra/curl is a fluent, Laravel-friendly PHP cURL wrapper for building and sending HTTP requests. Configure options with a query-builder-like API, use handy helpers for common settings, and integrate easily via service provider/facade (framework-independent core).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require ixudra/curl
    

    Laravel 5.5+ auto-discovers the package; for older versions, register the service provider and facade in config/app.php.

  2. First Use Case: Send a simple GET request:

    use Ixudra\Curl\Facades\Curl;
    
    $response = Curl::to('https://api.example.com/data')->get();
    echo $response;
    
  3. Key Entry Points:

    • Facade: Curl::to('url')->method() (e.g., get(), post()).
    • Utility Methods: withData(), withHeader(), asJson(), etc.
    • Response Handling: Default returns raw content; use returnResponseObject() for structured data.

Implementation Patterns

Core Workflows

  1. RESTful Requests: Chain methods for HTTP verbs and payloads:

    Curl::to('https://api.example.com/users/1')
        ->withData(['name' => 'John'])
        ->asJson()
        ->put();
    
  2. Authentication: Use utility methods for common auth headers:

    Curl::to('https://api.example.com/protected')
        ->withBearer('token123')
        ->get();
    
  3. File Uploads: Attach files to POST requests:

    Curl::to('https://api.example.com/upload')
        ->withData(['user_id' => 1])
        ->withFile('avatar', '/path/to/avatar.jpg', 'image/jpeg', 'avatar.jpg')
        ->post();
    
  4. Response Processing: Handle structured responses:

    $response = Curl::to('https://api.example.com/data')
        ->returnResponseObject()
        ->withResponseHeaders()
        ->get();
    
    if ($response->status === 200) {
        $data = json_decode($response->content, true);
    }
    
  5. Error Handling: Debug failed requests:

    try {
        $response = Curl::to('https://api.example.com/fail')
            ->enableDebug(storage_path('logs/curl_debug.log'))
            ->get();
    } catch (\Exception $e) {
        // Log or handle error
    }
    

Integration Tips

  • Service Container: Bind custom configurations:
    $app->singleton('curl.config', fn() => ['timeout' => 30]);
    Curl::setConfig($app->make('curl.config'));
    
  • Middleware: Extend the facade for project-wide defaults:
    Curl::macro('withProjectHeaders', function () {
        return $this->withHeaders([
            'X-Project-ID' => config('app.project_id'),
            'Accept' => 'application/json',
        ]);
    });
    
  • Testing: Mock responses with Http::fake() or use Curl::shouldReceive() in PHPUnit.

Gotchas and Tips

Pitfalls

  1. JSON Conflicts:

    • Issue: Using asJson() with file uploads corrupts multipart requests.
    • Fix: Avoid asJson() for file uploads; use raw form-data instead.
  2. Header Overrides:

    • Issue: Duplicate headers (e.g., Content-Type) may silently override each other.
    • Fix: Use withHeaders() with an associative array to ensure clarity:
      ->withHeaders(['Content-Type' => 'application/json', 'Accept' => 'application/json'])
      
  3. Proxy Authentication:

    • Issue: Proxy credentials may not persist across requests.
    • Fix: Reapply proxy settings per request or use a global config:
      Curl::setConfig(['proxy' => ['url' => 'proxy.example.com', 'auth' => ['user', 'pass']]]);
      
  4. Response Object Quirks:

    • Issue: withResponseHeaders() requires returnResponseObject().
    • Fix: Always chain these methods together:
      ->returnResponseObject()
      ->withResponseHeaders()
      
  5. Debug Logging:

    • Issue: Debug logs may overwrite files if not managed.
    • Fix: Use unique filenames or append mode:
      ->enableDebug(storage_path('logs/curl_debug_'.now()->timestamp.'.log'))
      

Debugging Tips

  1. Inspect Raw cURL Command: Use enableDebug() to generate a cURL command for manual testing:

    curl -X GET "https://api.example.com/data" -H "Authorization: Bearer token123"
    
  2. Check HTTP Status Codes: Always validate $response->status (or raw response for simple requests):

    if (str_starts_with($response, '{"error"')) {
        // Handle error
    }
    
  3. Timeout Handling: Set a default timeout in config or per request:

    Curl::setConfig(['timeout' => 10]); // Global
    // OR
    ->withOption(CURLOPT_TIMEOUT, 10); // Per request
    
  4. SSL/TLS Issues: Disable verification for testing (not production):

    ->withOption(CURLOPT_SSL_VERIFYPEER, false)
    ->withOption(CURLOPT_SSL_VERIFYHOST, false)
    

Extension Points

  1. Custom Options: Add project-specific cURL options via macros:

    Curl::macro('withCustomOption', function ($option, $value) {
        return $this->withOption($option, $value);
    });
    // Usage:
    ->withCustomOption(CURLOPT_FOLLOWLOCATION, true)
    
  2. Response Transformers: Extend the CurlService to auto-transform responses:

    class ExtendedCurlService extends \Ixudra\Curl\CurlService {
        public function get() {
            $response = parent::get();
            return json_decode($response, true);
        }
    }
    
  3. Event Listeners: Trigger events before/after requests:

    Curl::extend(function ($builder) {
        $builder->before(function ($request) {
            // Log request details
        });
    });
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui