Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel HTTPS routes

Tags:

php

laravel-5

today I decided to move my website to HTTPS. Early my website work on HTTP.

My problem is in misunderstood how Laravel pass HTTP and https in helpers function route('name')

I change my website URL in config/app.php to https://www.domain.name and I think, this solution helps me. But I got a strange result.

In php artisan tinker if I pass route('ROUTE.NAME') I got right link https://www.domain.name/route/path but in blade template I got http://www.domain.name/route/path

The same situation with \URL::to('/')

Maybe someone can explain to me why this happened?

like image 839
Mgorunuch Avatar asked Jun 07 '17 10:06

Mgorunuch


2 Answers

The @dekts response is correct, but the "right" place to put this kind of stuff is the "app/Providers/AppServiceProvider.php" on the boot method.

//file: app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\URL;

class AppServiceProvider extends ServiceProvider {

    public function boot()
    {
        if (app()->environment('remote')) {
            URL::forceScheme('https');
        }
    }

    ...
}

You can also add a new variable on your ".env" file, something like:

#file: .env
FORCE_HTTPS=true

And change the condition to

//file: app/Providers/AppServiceProvider.php
public function boot()
{
    if(env('FORCE_HTTPS',false)) { // Default value should be false for local server
        URL::forceScheme('https');
    }
}

Hope this help.

edit: corrected forceSchema to forceScheme as noted on the comments. ;)

like image 80
Leles Avatar answered Oct 30 '22 09:10

Leles


Automatic detection http/https

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Request;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
      /* Use https links instead http links */
      if (Request::server('HTTP_X_FORWARDED_PROTO') == 'https')
      {
         URL::forceScheme('https');
      }
    }
}
like image 32
Maxim Avatar answered Oct 30 '22 11:10

Maxim