Laravel Restrict Access Per IP

There are valid reasons why someone may want to restrict the users who can use a web application. One of the most efficient restriction is based on IP addresses. It is based on your user having a static IP address. Laravel already has a helper method, which makes obtaining the IP address of the current user easy. And here is how to restrict access to a specific IP or to group of IPs:

1. Laravel. Restrict Access To Single IP Address

if (\Request::ip() != '79.79.9.246') {
    die('No access allowed');
}

2. Laravel. Restrict Access To Multiple IP Addresses

$allowedIps = ['79.79.9.246', '179.79.9.246', '23.79.9.246'];

if (in_array(\Request::ip(), $allowedIps) == false) {
    die('No access allowed');
}

3. Where to place the IP based restriction in Laravel

You can add this code above pretty much anywhere:

- Directly at the beginning of the routing file;

- Filter for the router;

- Separate middleware;

- In the constructor of every controller, or only the ones we want to restrict the access to.

4. Laravel alternatives

You can also allow the IPs directly in the server config files, or the .htaccess file if you are using Apache.

 

Please Do Not Reprint This Article

This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form. Links to this article are welcome

Other Related Articles