Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 subdomain routing on any domain

In a laravel 5 application, I'm trying to make a route for subdomain without knowing the domain.

Route::group(array('domain' => 'subdomain.domain.tld'), function() {
    Route::get('/', 'testController@getTest2');
});
Route::get('/', 'testController@getTest1');

This kind of routing works, and I get getTest2() called for subdomain and getTest1() for calling without subdomain.

Now, I'd like this to work with wildcard domain, but without sending parameters to controller, so the application in dev enviroinment can be on any domain. (I also considered using .env for storing domain, but that seems too much hassle for just routing)

I've tried

array('domain' => 'subdomain.{domain}.{tld}')

Which requires parameters on controller methods. and I've tried

array('domain' => 'subdomain.{domain?}.{tld?}')

Which doesn't require parameters, but sends them anyway, so my actual route parameters get shifted.

I've also seen http://laravel-tricks.com/tricks/dynamic-subdomain-routing, but I don't like the idea of handling my domains in filters.

Is there any other way to have a wildcard domain that will be ignored once route group is handled?

like image 836
YomY Avatar asked Jul 13 '15 06:07

YomY


2 Answers

The best way i've found to do this is to create a middleware that removes specific parameters from your route. For instance, in your case:

class Subdomain {
  public function handle($request, Closure $next) 
  {
    $route = $request->route();
    $domain = $route->parameter('domain');
    $tld = $route->parameter('tld');

    //do something with your params

    $route->forgetParameter('domain');
    $route->forgetParameter('tld');
    return $next($request);
  }
}

//inside your Kernel.php, make sure to register the middleware
protected $routeMiddleware = [
  'subdomain' => \App\Http\Middleware\Subdomain::class,
];

Route::group(['middleware' => 'subdomain', 'domain' => 'subdomain.{domain}.{tld}'], function () {
  Route::get('/', function () {
    dd(func_get_args()); //no args, because it was removed in the middleware
  });
});
like image 55
jpcamara Avatar answered Nov 17 '22 23:11

jpcamara


Just so you know you can do

'domain' => '{subdomain}.{domain}.{tld}' 

and that will route a.domain.com and b.domain.com to all he same routes / same controllers and you can do your logic inside of that controller.

I would use a middleware like suggjested above to remove the domain and tld from the request or else every modeling is going to have to look like.

public function myMethod($subdomain, $domain, $tld, $id)

assuming your route needs an $id or any other route parameter.

One other thing you might be interested in is Explicit Form Model Binding.

like image 37
hcker2000 Avatar answered Nov 18 '22 00:11

hcker2000