I have been doing some work with Laravel lately and needed to force a site to use https for everything. One of the first problems I encountered was figuring out how to force https in Laravel for linked stylesheets, javascript assets, etc…
I found a few different solutions, but none of them solved the issue. I was able to combine a couple of different approaches and found one that worked really well.
HTTPS in Laravel | Setup Asset and URL Helpers
Set an environment variable in your https environments
Since most people develop in a localhost/non https environment, I found that setting a boolean environment variable takes away the pain. I called mine REDIRECT_HTTPS
. I set the value to true
.
Update your app/Providers/AppServiceProvider.php
file
As you will see below, I check the environment variable to enable the https settings. If set to true, the https prefix is added to your asset urls.
namespace App\Providers;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot(UrlGenerator $url)
{
if(env('REDIRECT_HTTPS')) {
$url->formatScheme('https');
}
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
if(env('REDIRECT_HTTPS')) {
$this->app['request']->server->set('HTTPS', true);
}
}
}
Import your assets normally
After your have everything in place, you can just import your assets normally and they will load with https in https environments and http in non-https environments depending on your environment variable.
Learn Laravel
Before I started working on this project, my knowledge of the Laravel framework was very limited. I worked through a few examples, but was still left with a lot of questions about facades, helpers, the dependency injection mechanism, database migrations, security, etc…
When learning a new framework, my goto is normally Pluralsight. I will be writing a post with more training resources than the following, but wanted to recommend the following courses:
- Getting Started with Laravel (PHP Framework) – The Basics
- Getting Started with Laravel (PHP Framework) – Models and Data
- RESTful Web Services with PHP and Laravel
As always, please comment with questions, etc…
thank for sharing, you are saved my life
Two years after, still the best solution I found