Black Friday sale is now on! 50% off Laravel: The Modular Way. Learn more

Laravel force https with url helper

David Carr

Laravel Framework PHP & MySQL Tutorials

    using the url() helper is great for creating full http links, I use this for all links, when working locally http is fine but when going online you want to use https instead. 

    The url helper accepts 3 params the path, parameters and a boolean which determines where to use https or http.

    function url($path = null, $parameters = [], $secure = null)
    {
        if (is_null($path)) {
            return app(UrlGenerator::class);
        }
    
        return app(UrlGenerator::class)->to($path, $parameters, $secure);
    }

    Alternatively, you can use secure_url() instead. This calls the url() method and passed any params and also sets the third parm to true to use https.

    function secure_url($path, $parameters = [])
    {
        return url($path, $parameters, true);
    }

    The only problem with this is you have to update every instance of your url() call across your application. Not a problem if you develop with https from the start.

    Another way to tell Laravel to use https when not using a local environment, this way you can still use your existing url() calls without any changes. To accomplish this open app/Providers/App/ServiceProvider.php

    Import UrlGenerator:

    use Illuminate\Routing\UrlGenerator;

    Next in the boot method inject UrlGenerator $url and inside the method check if the environment setting APP_ENV defined in .env is not equel to local. As long as it's not set to local force the scheme https to be used. 

    public function boot(UrlGenerator $url)
    {
        if (env('APP_ENV') !== 'local') {
            $url->forceScheme('https');
        }
    }

    This is in place url() will always return https.

    Laravel Modules Book by David Carr

    Help support the blog so that I can continue creating new content!

    Subscribe to my newsletter

    Subscribe and get my books and product announcements.

    © 2009 - 2022 DC Blog. All code MIT license. All rights reserved.