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() != '') {
    die('No access allowed');

2. Laravel. Restrict Access To Multiple IP Addresses

$allowedIps = ['', '', ''];

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.