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.

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.

Previous
No JavaScript, No Website
Next
Practical Laravel. Cleaning Up

Keep Reading

Explore more articles and insights

Ork: SSH Server Automation in Go

Ork: SSH Server Automation in Go

Read Article
Deno Deploy Killed My Start Page

Deno Deploy Killed My Start Page

Read Article
Back to Golang: Why I Switched From Static to Dynamic Again

Back to Golang: Why I Switched From Static to Dynamic Again

Read Article
View All Blog Posts