How to check access to Laravel project by IP address

From time to time I see a need of restricting the access to a website by IP address, whether it’s local network or a particular set of specific computers, like home/office. What’s the best way to do that in Laravel?

There’s no “official” prepared solution for this in Laravel core, but we can use a concept of Middleware to create our own class for restrictions.

So we run:

Then we go into generated app/Http/Middleware/IPAddresses.php and add this:

There are a few things to notice here:

  • There are multiple ways to get client’s IP address – you can also use $_SERVER[‘REMOTE_ADDR’] from PHP directly or something more complicated like this;
  • Instead of abort(403); you can do something like redirect() to some page with message or errors.

To user your Middleware class, you need to register it in app/Kernel.php:

This approach is not really flexible, so if you want something more robust, check this snippet by Bobby Bouwmann on Laracasts forum:

Finally, you can use a package by Antonio Ribeiro called Firewall – it allows you to perform much more restrictions than just IP addresses.

Want to generate Laravel adminpanel online?
You don't need any packages to do that!

2 thoughts on “How to check access to Laravel project by IP address

Leave a Reply

Your email address will not be published. Required fields are marked *