Laravel force https with url helper

David Carr

2 min read - 1st Jan, 2018

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.

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.