In the Laravel framework, you can retrieve the client’s IP address using the ip()
method provided by the Request object. This object contains details about the incoming HTTP request, including the client’s IP address.
Laravel makes it easy to access the Request object in controllers, middleware, routes, and even views.
To get the IP address, simply call the ip()
method on the Request instance — it will return the IP address as a string.
We’ll create a controller, define a method, and set up a route.
Step 1: Open your terminal and run the command below to create a controller named IPAddressController
:
php artisan make:controller IPAddressController
Once the controller is created, we need to define a getLocalIP()
method inside the IPAddressController
. In this method, we will retrieve the client’s IP address using the Request object.
Step 2: Open app/Http/Controllers/IPAddressController.php
and update it like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class IPAddressController extends Controller
{
public function getLocalIP(Request $request)
{
// Retrieve the client's IP address
$clientIP = $request->ip();
// Return the IP address as a response
return "Client IP Address: ". $clientIP;
}
}
Step 3: Define the route
Now, let’s create a route to access this controller method.
Open the routes/web.php file and add the following route:
use App\Http\Controllers\IPAddressController;
Route::get('/local-ip-address', [IPAddressController::class, 'getLocalIP']);
– This route maps the /local-ip-address
URL to the getLocalIP()
method in the IPAddressController.
Step 4: Run the Laravel development server
To test the method, start the Laravel application on the development server. In your terminal, run the command:
php artisan serve
– Once the server is running, open the following URL in your browser:
http://127.0.0.1:8000/local-ip-address
– You should see the client’s IP address displayed on the screen.
All Comments