If your Laravel application is behind Cloudflare and you want to get user ip with method $request->ip(), or $request->getClientIp() in many cases you will not get real client ip but the cloudflare server ip.

This is actually a feature on cloudflare side described here

Here is how to get real client IP - simple way.

As described in the cloudflare link above there are several ways how to get real user IP but the most easiest one is just by using request headers.

Cloudflare is actually sending real user IP but in a different header, the param that we want to us is called "HTTP_CF_CONNECTING_IP"

So, knowing this we can get the real user IP by reading that header:

                    // Laravel
$request->server('HTTP_CF_CONNECTING_IP');

// plain PHP
$_SERVER['HTTP_CF_CONNECTING_IP']
                  

Nice and easy... but what about local environment, isn't this going to throw an error because on my local machine this header does not exist? 
Yes, true!


So, we will just modify it a little bit to use "regular" way of getting IP:

                    public function getUserIP($request){
 if( !empty( $request->server('HTTP_CF_CONNECTING_IP') ) ){
   
     return $request->server('HTTP_CF_CONNECTING_IP');

 }else{

   return $request->getClientIp();

 }
}

// for plain php

function getUserIP($request){
 if( !empty( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ){
   
     return $_SERVER['HTTP_CF_CONNECTING_IP'];

 }else{

   return $_SERVER["REMOTE_ADDR"];

 }
}
                  

Cloudlfare is also sending information about user country, if you want to find out how to get that param in laravel - please read this article: