phplaravelhttpsurl-routinglaravel-4.2

Laravel 4.2: Force URL to be rendered as HTTP or HTTPS


We have a simple route defined like the following one:

Route

// Home
Route::get('/home', [
    'as' => 'home::index',
    'uses' => 'IndexController@home'
]);

View

<a href="{{ route('home::index') }}">Home</a>

We need to force our link/route in view rendered as HTTP or in some cases as HTTPS route e.g. http://host.domain/home or https://host.domain/home.

We cannot use URL::forceSchema("http") or URL::forceSchema("https") since we need to force HTTPS on a HTTP page and HTTP on a HTTPS page. We have a multidomain application. Some domains running via HTTP some via HTTPS. A link to different domain / "application section" can be placed everywhere. A domain running via HTTPS cant be accessed via HTTP. A domain running on HTTP cant be accessed via HTTPS

How to force a route rendered as a specific hypertext protocol?


Solution

  • There is a section in Laravel documentaion under title Forcing A Route To Be Served Over HTTPS. It does not mention generated URL for the route, but I can see in Illuminate\Routing\UrlGenerator code this settings is respected in getRouteScheme method. So adding a new value http/https to the action array should do the trick:


    Force route to be rendered as HTTP:

    Route::get('/home', [
        'as' => 'home::index',
        'uses' => 'IndexController@home',
        'http'
    ]);
    

    Force route to be rendered as HTTPS:

    Route::get('/home', [
        'as' => 'home::index',
        'uses' => 'IndexController@home',
        'https'
    ]);
    

    Now route('home::index') should generate URL based on schema you defined.