Creating a route in Laravel using subdomain and domain wildcards

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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  IlluminateHttpRequest  $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);
    }
}

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x