How to redirect requests to HTTPS in Laravel 5

I know we can achieve same with other methods but I am going do it with the Laravel’s Middleware. So let’s create Middleware called ForceHttpProtocol.

How it will work

Our ForceHttpProtocol middleware will redirect every request to https if – The current request comes with no security protocol means HTTP and If your environment is equaled to prod. So, just adjust the settings according to your preferences.

Create middleware

Using your Terminal, navigate to your project’s root directory and issue the following artisan command:

Now, using your editor of choice, change the newly created /app/Http/Middleware/ForceHttpProtocol.php so it look like this:

Next update /app/Http/Kernel.php adding the 'App\Http\Middleware\ForceHttpProtocol' instruction which will make Laravel aware of your custom middleware:

If you want to apply middleware only on specific routes you just have to assign middleware to routes by adding 'App\Http\Middleware\ForceHttpProtocol' instruction to $routeMiddleware array.

If route middleware – just use your middleware as you’re used to:

That is it.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Published by Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.

Join the Conversation


Leave a comment

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