Skip to main content

Command Palette

Search for a command to run...

Laravel: Get the Real IP from the cloudflare

Published
1 min read

How to get the real IP behind the cloudflare proxy? Easy

class ReplaceCloudflareIp
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $cfHeader = $request->header('CF-Connecting-IP');
        $request->headers->set('x_forwarded_for', $cfHeader);
        Request::setTrustedProxies(
            ['REMOTE_ADDR'],
            Request::HEADER_X_FORWARDED_FOR
        );
        return $next($request);
    }
}

don’t forget to register it in “bootstrap/app.php”

 $middleware->web(append: [
           //
            ReplaceCloudflareIp::class,
        ]);