almo
almo

Reputation: 6367

Laravel add domains to controller routes

I have a Laravel App and a domain to access it. The Domain points to the public folder and executes the '/' route which then executes a certain method 'BaseController@index' in a controller.Now I want to add another domain. But this domain should execute another method 'AppController@run' (route can be '/app/run/.

How can I achieve this?

I created a vhost for this other domain that points directly to public/app/run. This works but the browser shows domain.com/app/run which I don't like.

So I think what I have do do is let this domain point to public and then in my routes file say that this domain shell execute 'AppController@run'

Or in the worst case it points to the '/' route and then inside the BaseController@index method I have to check what domain is accessing. But this seems not good to me.

Any ideas? I wonder why I can't find a lot on Google since this should not be only important to me.

Upvotes: 1

Views: 15218

Answers (2)

Amir Khalil
Amir Khalil

Reputation: 307

Laravel Framework 5.7.2

I wanted a separate domain for my API.

My solution was to edit the mapApiRoutes() in Providers/RouteServiceProvider.php

    protected function mapApiRoutes()
{
    //This is what we're changing to Route:domain('www.sub.domain.com')
    Route::prefix('api')
         ->middleware('api')
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));
}

and the function should look something like this:

protected function mapApiRoutes()
{
    Route::domain('www.sub.domain.com')
         ->middleware('api')
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));
}

You will also need to reconfigure your apache depending on what you're trying to accomplish.

Hope this helps.

Upvotes: 1

lukasgeiter
lukasgeiter

Reputation: 152860

First, all vhosts should have set the document root to the public public directory, otherwise Laravel won't bootstrap correctly.

Then you can add specific routes for that domain. For example:

Route::group(['domain' => 'seconddomain.com'], function(){
    Route::get('/', 'AppController@run');
});

Now if you go to seconddomain.com run() in AppController will be called

Upvotes: 4

Related Questions