I'm working on a multitenant, multidomain Laravel project and of course the base of the software is the same for all users, but I have several users who asking me very specific things and don't want to build these features into the main codebase.
I separated the models, controllers, and migrations to namespaces like this:
app/Models/ClientSpecific/{ClientName}/{ModelName}
app/Http/Controllers/ClientSpecific/{ClientName}/{ModelName}Controller
database/migrations/client-specific/{ClientName}/{MigrationFile}
Going along this logic I want to add routes and I want to store it in separate files too:
routes/client-specific/{domainname.com}/api.php
routes/client-specific/{domainname.com}/web.php
routes/client-specific/{anotherdomain.com}/api.php
routes/client-specific/{anotherdomain.com}/web.php
routes/client-specific/{thirddomain.com}/api.php
How can load these route files only that domain what is called and only there? Is there any best practice to add domain based routing in Laravel? Or just add a domain check to the RouteServiceProvider.php
based on $_SERVER['SERVER_NAME']
?
My Answer:
One common approach to achieve domain-based routing in Laravel is to use route groups with domain constraints in your RouteServiceProvider.php file. Here's an example of how you can set up domain-based routing in Laravel:
1. Create separate route files for each domain in the routes directory:
- routes/domain1.com/web.php
- routes/domain1.com/api.php
- routes/domain2.com/web.php
- routes/domain2.com/api.php
2. In your RouteServiceProvider.php file, you can load the routes based on the current domain using domain constraints:
php
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
}
protected function mapApiRoutes()
{
Route::middleware('api')
->domain('domain1.com')
->namespace($this->namespace)
->group(base_path('routes/domain1.com/api.php'));
Route::middleware('api')
->domain('domain2.com')
->namespace($this->namespace)
->group(base_path('routes/domain2.com/api.php'));
}
protected function mapWebRoutes()
{
Route::middleware('web')
->domain('domain1.com')
->namespace($this->namespace)
->group(base_path('routes/domain1.com/web.php'));
Route::middleware('web')
->domain('domain2.com')
->namespace($this->namespace)
->group(base_path('routes/domain2.com/web.php'));
}
This way, Laravel will load the appropriate route file based on the current domain when a request is made. Make sure to replace 'domain1.com' and 'domain2.com' with the actual domain names you are using.
By using this approach, you can keep your routes organized and separated by domain, making it easier to manage and maintain your codebase for a multitenant Laravel project.
Rate this post
5 of 5 based on 5064 votesComments