Laravel Redirect To https

Redirect http urls to https

If you are working on a website where you need to re-direct http urls to https using laravel framework you need to understand how laravel handle a request first.

Every request in laravel before it hits to your controller it goes through middleware if defined one. We have to create a new middleware for our functionality.

How to create a laravel middleware?

To create a new middleware that redirects http url to https open terminal window when being in laravel project root and run following command:

# run this command in laravel project root dir
$ php artisan make:middleware HttpsProtocol​

Above command will create a new middleware file in app/Http/Middleware. Open HttpsProtocol.php file and make following changes.

<?php

namespace App\Http\Middleware;

use Closure;

class HttpsProtocol
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->secure()) {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }
}

Basically, we check to see if incoming request is not secure meaning http and if it is then redirect it to https request. A good developer always know when to use middleware.

You should not use middleware if it has nothing to do with request object.

To learn more about how to use middleware read following laravel official documentaion:

Laravel Middlewares