Last updated on September 30, 2023
In Laravel framework, we can retrieve client’s IP address through the ip()
method from the Request
object. It holds information about the incoming HTTP request, including the IP address of the client. Laravel allows us to access Request
object in the controller’s method, middleware, routes and views.
To retrieve the IP address, simply call the ip()
method on the Request object, which returns the IP address as a string.
Let’s retrieve the ip address, for that we will be creating controller, method and route. Open the terminal and run below command to create IPAddressController
php artisan make:controller IPAddressController
Once the controller created, we need to create getLocalIP()
method in the controller in which we will be retrieving the IP address.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class IPAddressController extends Controller
{
public function getLocalIP(Request $request)
{
$clientIP = $request->ip();
return "Client IP Address: ". $clientIP;
}
}
Next, this method needs a web route so that we can run it through the URL. Open the web.php from routes directory and add below route.
Route::get('/local-ip-address', [IPAddressController::class, 'getLocalIP']);
In the next step, we need to run the getLocalIP()
method. To do that run below command that will be running the Laravel application on the development server.
php artisan serve
Then open this URL http://127.0.0.1:8000/local-ip-address
in the browser which will be displaying client’s IP address.
Conclusion:
In this article, we explain how to retrieve the client’s IP address in Laravel using the ip() method. We also provide an example by creating a controller, method, and route for retrieving the client’s IP address.