Alternative Way To Create Multi-Site Setups With Laravel With A Single Codebase

Even though you can easily point multiple domains at a Laravel installation, sometimes you want the sites to share different routing and controller logic, depending on the domain name the application is being served from.

One obvious way to do this would be to use middleware to examine each request and handle the logic according to your needs, but that can get tedious.

The other, simpler way, is to modify the app/Providers/RouteServiceProvider.php file and change the logic for mapApiRoutes() and mapWebRoutes().

You will need to fetch the hostname for the request from the request() helper  and include the appropriate route for that.

$http_host = request()->getHttpHost();

This can create a two inter-related issues:

  1. Named routes are not shared in the application. So, if you have a named route called ‘blogs.index’ in one route mapping and it is missing in the other, you will not be able to call the ‘blogs.index’ route from the latter. This will lead to a bit of duplication of route names where it is needed, but it is worth the trade off.
  2. As a consequence, if you use an accessor with a named route in a model (example: $post->url which is the getUrlAttribute() method in the Post model), you have to make sure either the route names are duplicated between the routes or check for the host name to see which name to call.