Force HTTP or HTTPS scheme on Laravel automatically

Laravel Framework
Laravel Framework

In Laravel, when you want to load assets on different schemes like HTTP or HTTPS, you have to use asset() or secure_asset() helpers to load assets properly. That requires a conditional check on the code, and not so cool.

To resolve it, it is better to tell Laravel, UrlGenerator to be exact where URL routing happens, we can force scheme based on environment config.

For example, setup a key on .env


and then require UrlGenerator to force appropriate URL scheme from config variable. We can write it inside a ServiceProvide for example, AppServiceProvider

use Illuminate\Routing\UrlGenerator;

class AppServiceProvider extends ServiceProvider

    public function boot(UrlGenerator $url)
        if(env('REDIRECT_HTTPS')) {

So whenever you want to use HTTPS, just set the config variable to true, otherwise, make it false. Often, you will use HTTP on localhost, and HTTPS on production.