PHP & MySQL, Tutorials, Laravel Framework

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.

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.