Laravel Framework | PHP & MySQL | Tutorials

David Carr

Laravel force https with url helper

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.

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

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