Reputation: 5069
With Laravel 5.2, I would like to set up a wildcard subdomain group so that I can capture a parameter. I tried this:
Route::group(['middleware' => ['header', 'web']], function () {
Route::group(['domain' => '{alias}.'], function () {
Route::get('alias', function($alias){
return 'Alias=' . $alias;
});
});
});
I also tried ['domain' => '{alias}.*']
.
I'm calling this URL: http://abc.localhost:8000/alias
and it returns an error of route not found.
My local environment is localhost:8000
using the php artisan serve
command. Is it possible to set this up locally without an actual domain name associated to it?
Upvotes: 0
Views: 2287
Reputation: 6534
I had a similar task before. If you want to catch any domain, any format - unfortunately you cannot do it directly in the routes file. Routes file expects at least one portion of the URL to be pre-defined, static.
What I ended up doing, is creating a middleware that parses domain URL and does some logic based on that, eg:
class DomainCheck
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$domain = parse_url($request->url(), PHP_URL_HOST);
// Remove www prefix if necessary
if (strpos($domain, 'www.') === 0) $domain = substr($domain, 4);
// In my case, I had a list of pre-defined, supported domains
foreach(Config::get('app.clients') as $client) {
if (in_array($domain, $client['domains'])) {
// From now on, every controller will be able to access
// current domain and its settings via $request object
$request->client = $client;
return $next($request);
}
}
abort(404);
}
}
Upvotes: 1
Reputation: 381
On line 2 where you have:
Route::group(['domain' => '{alias}.'], function() {
Replace it with the following:
Route::group(['domain' => '{alias}.localhost'], function() {
It should work after that.
Upvotes: 1