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 Cloudflare Laravel Package

monicahq/laravel-cloudflare

Laravel middleware that automatically trusts Cloudflare proxy IP ranges so client IPs and forwarded headers are handled correctly. Drop-in replacement for Laravel’s TrustProxies, with an optional callback to customize how proxy lists are loaded.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require monicahq/laravel-cloudflare
    
  2. Replace the default TrustProxies middleware in bootstrap/app.php:
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->replace(
            \Illuminate\Http\Middleware\TrustProxies::class,
            \Monicahq\Cloudflare\Http\Middleware\TrustProxies::class
        );
    })
    
  3. Refresh Cloudflare IPs (run once after setup):
    php artisan cloudflare:reload
    

First Use Case

  • Verify Cloudflare IPs are trusted: Use php artisan cloudflare:view to confirm the cached IPs.
  • Test IP detection: Deploy to Cloudflare and check if request()->ip() now returns the correct client IP (via CF-Connecting-IP header).

Implementation Patterns

Core Workflow

  1. Middleware Integration:

    • The package replaces Laravel’s default TrustProxies middleware, leveraging Cloudflare’s IP ranges to trust proxies dynamically.
    • Key: The middleware merges Cloudflare’s IPs with any existing trusted proxies (e.g., from .env or other middleware).
  2. Caching Strategy:

    • Cloudflare IP ranges are fetched once and cached (default: 24 hours).
    • Best Practice: Schedule a daily refresh via routes/console.php:
      Schedule::command('cloudflare:reload')->daily();
      
  3. Custom Proxy Logic:

    • Override the default proxy source by defining a callback in AppServiceProvider::boot():
      LaravelCloudflare::getProxiesUsing(fn() => customProxyLogic());
      
    • Useful for integrating with third-party IP services or internal whitelists.
  4. IP Replacement (Advanced):

    • Enable replace_ip in config/laravelcloudflare.php to replace the request IP with CF-Connecting-IP:
      'replace_ip' => true,
      
    • Note: Requires CF-Connecting-IP header to be present (Cloudflare’s default behavior).

Integration Tips

  • Testing:
    • Disable the package in tests via .env:
      LARAVEL_CLOUDFLARE_ENABLED=false
      
    • Mock CloudflareProxies for unit tests:
      LaravelCloudflare::getProxiesUsing(fn() => ['1.1.1.1/32']);
      
  • Multi-Environment:
    • Publish the config (php artisan vendor:publish --provider="Monicahq\Cloudflare\TrustedProxyServiceProvider") to customize cache TTL or proxy behavior per environment.

Gotchas and Tips

Pitfalls

  1. Cache Staleness:

    • Cloudflare’s IP ranges change infrequently, but always test after cloudflare:reload in staging/production.
    • Debug: Use php artisan cloudflare:view to verify cached IPs match Cloudflare’s official list.
  2. Header Conflicts:

    • If CF-Connecting-IP is missing, the middleware falls back to the original IP. Ensure Cloudflare is properly configured to forward this header.
  3. Middleware Order:

    • The package must replace TrustProxies entirely. Mixing it with other proxy middleware (e.g., TrustProxies with custom proxies) may cause conflicts.
  4. Laravel Version Mismatches:

    • Laravel 9/10: Use v3.x. Laravel 11+: Use v4.x. Check the compatibility table for breaking changes.

Debugging

  • Log Proxy IPs: Add this to a middleware to log trusted proxies:
    \Log::debug('Trusted Proxies:', config('trustedproxies.proxies'));
    
  • Check Headers: Verify CF-Connecting-IP is present in requests:
    \Log::debug('CF Headers:', request()->header());
    

Extension Points

  1. Custom Proxy Sources:

    • Extend CloudflareProxies to fetch IPs from an API or database:
      class CustomCloudflareProxies extends \Monicahq\Cloudflare\CloudflareProxies {
          public function load() {
              return $this->fetchFromCustomSource();
          }
      }
      
    • Register the callback in AppServiceProvider:
      LaravelCloudflare::getProxiesUsing(fn() => (new CustomCloudflareProxies())->load());
      
  2. Dynamic TTL:

    • Override the cache TTL in config/laravelcloudflare.php:
      'cache_ttl' => 1440, // 1 hour (default: 86400 = 24h)
      
  3. IP Whitelisting:

    • Combine with TrustProxies’s proxies config to merge Cloudflare IPs with static IPs:
      TRUSTED_PROXIES=192.168.1.0/24,1.1.1.0/24
      
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime