Creating a multi-tenancy application with Laravel that supports multiple domains can be a complex task, but it's definitely achievable. Here's a high-level approach to how you might structure your application to support this:
-
Domain-Based Configuration: You'll need to determine which tenant is being accessed based on the domain. You can do this by creating a middleware that checks the domain and sets the configuration accordingly.
-
Database Connections: Each tenant will have its own database. You can dynamically configure the database connection based on the domain.
-
Resource Customization: For custom CSS/JS/views, you can use a similar approach to the database connections by determining which resources to load based on the domain.
Here's a simplified example of how you might implement this:
- Middleware for Tenant Identification:
namespace App\Http\Middleware;
use Closure;
use App\Models\Tenant;
class IdentifyTenant
{
public function handle($request, Closure $next)
{
$domain = $request->getHost();
$tenant = Tenant::where('domain', $domain)->firstOrFail();
// Set the database connection for the tenant
config(['database.connections.tenant.database' => $tenant->database]);
// Set the path for custom resources
config(['view.paths' => [resource_path('views/tenants/' . $tenant->id), resource_path('views')]]);
return $next($request);
}
}
- Dynamic Database Connection:
In your config/database.php, you can set up a tenant connection template:
'tenant' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
// 'database' will be set dynamically
'username' => env('DB_USERNAME', 'your_username'),
'password' => env('DB_PASSWORD', 'your_password'),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
You would then switch to this connection in your models or at runtime as needed:
DB::connection('tenant');
- Custom Resource Loading:
As shown in the middleware, you can dynamically set the view paths. You can do the same for assets by creating a helper function that generates URLs for assets based on the tenant.
Remember to register your middleware in the Kernel.php file and apply it to your routes.
This is a very high-level overview and there are many details to consider, such as tenant creation, database migrations, domain routing, and more. You might also want to look into packages that handle multi-tenancy in Laravel, such as tenancy/tenancy or spatie/laravel-multitenancy, which can greatly simplify some of these tasks.
Remember to thoroughly test each part of your multi-tenancy system to ensure that tenants are completely isolated and that there are no data leaks between them.