Gunnar
Gunnar

Reputation: 759

Laravel domain routing in production and dev

I have a working Laravel 5.2 project using sub-domain routing that I run locally (homestead) and in production (forge configured with wildcard subdomain routing on AWS). My local project has a host file entry for admin.project.app and successfully routes to admin.project.app while my production version routes to admin.project.com.

My local .env file has the variable APP_ENV=local while my .env on forge has the variable APP_ENV=production. So far, so good.

The problem I am having is that I would expect Laravel to resolve the domain based on the fact that I am running locally (with the extension of .app) or in production (with the extension of .com) using this type of wildcard routing rule:

Route::group(['domain' => 'admin.project.*'], function()
{
    Route::get('/', 'HomeController@index');

});

The problem I am having is that either Laravel, Ngnix, AWS, or Forge is requiring me to explicitly route like this, which seems completely redundant:

if (App::environment('local')) {
    Route::group(['domain' => 'admin.project.app'], function()
    {
        Route::get('/', 'HomeController@index');

    });
}else{
    Route::group(['domain' => 'admin.project.com'], function()
    {
        Route::get('/', 'HomeController@index');

    });

}

Or maybe my expectations are just wrong ;) Any pointers as to what I may be doing wrong are greatly appreciated!

Upvotes: 3

Views: 6290

Answers (2)

Bogdan
Bogdan

Reputation: 44526

The really easy solution would be to use a ternary operator to determine the TLD and use that in the group's domain attribute:

Route::group(['domain' => 'admin.project.' . ((env('APP_ENV') == 'production') ? 'com' : 'app')], function()
{
    Route::get('/', 'HomeController@index');
});

Avoiding duplication of code and adding additional environment variables.

Upvotes: 5

Jeff
Jeff

Reputation: 25221

Does the same thing happen with a route param {} instead of *? I am not sure that laravel routing supports *:

Route::group(['domain' => 'admin.project.{tld}'], function()
{
    Route::get('/', 'HomeController@index');
});

https://laravel.com/docs/5.2/routing#route-group-sub-domain-routing

Or what if you just used the domain as an ENV variable? In your env file locally, add:

APP_DOMAIN=admin.project.app

Then in the route file:

Route::group(['domain' => env("APP_DOMAIN","admin.project.com")],function(){

});

Upvotes: 2

Related Questions