Force redirect in laravel 5,6,7,8 [ Solution ]

    By: Manu
    2 years ago

    i believe this will work for you if you are looking to force redirect user to "https". So let's see how we can force redirect in laravel 5,6,7,8.


    Redirecting user to https using "App service Provider"

    Go under
    // app/Providers/AppServiceProvider.php
    
    // and in boot function add this code
    
    public function boot(UrlGenerator $url)
    {
        if (env('APP_ENV') !== 'local') {
            $url->forceScheme('https');
        }
    }
    

    In your ".env" file "App_ENV" if anything otherthan local then it will redirect the user.



    Second method

    Redirecting user to https using "Route service Provider"

    Go under
    
    // app/Providers/RouteServiceProvider.php
    
    // here make boot function this way
    
    public function boot()
    {
        if (env('APP_ENV') === 'production') {
            $url = \Request::url();
            $check = strstr($url, "http://");
            if ($check) {
                $newUrl = str_replace("http", "https", $url);
                header("Location:" . $newUrl);
    
            }
        }
    
        parent::boot();
    }
    


    Here In your ".env" file "App_ENV" should be "production". then app will load in "https".

    Hope this solves the issue