Laravel generate secure https URL from route
UPDATE: As pointed out in the comments, a simpler way of doing this would be adding URL::forceSchema('https');
for Laravel version between 4.2-5.3 or URL::forceScheme('https');
for version 5.4+ in the boot
method of your AppServiceProvider
file.
Old answer:
It's actually entirely possible and there's only one line of code needed to accomplish that.
Laravel doesn't check the presence of SSL by itself, it depends on Symfony. And there goes our key to making it believe that the current request is secure.
The thing is, we have to set the HTTPS
server param
to true and the easiest method is to paste the following code in the boot
method of your AppServiceProvider
:
$this->app['request']->server->set('HTTPS', true);
In my very case, I only need to force SSL in production, the local env should still work on http. This is how I force SSL only on production:
$this->app['request']->server->set('HTTPS', $this->app->environment() != 'local');
By the way, mind those terms, you may need them in the future.
Laravel 8
I recently resolved this by modifying this file:
app/Providers/AppServiceProvider.php
in the method boot()
add the following:
URL::forceScheme('https');
Add the use in the top:
use Illuminate\Support\Facades\URL;
to work in your local environment you can leave it like this:
public function boot()
{
if(env('APP_ENV') !== 'local') {
URL::forceScheme('https');
}
}
Note: Don't forget to set your env variable APP_ENV
with prod
for the production file.
APP_ENV=prod