Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

Laravel force https with url helper

David Carr

Laravel Framework Tutorials PHP & MySQL

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 Your Logo Your Logo Your Logo

Become a sponsor

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

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.