To create a multi-site application in Laravel where different domains point to the same application but display different content based on the domain, you can follow these steps:
-
Domain Routing: Use Laravel's routing capabilities to handle different domains. You can use the
Requestfacade to determine the current domain and route requests accordingly. -
Middleware: Create a middleware to detect the domain and set configurations or load specific data based on the domain.
-
Database Structure: You might want to have a
sitestable in your database to store information about each site, such as domain name, settings, and any other site-specific data. -
Service Provider: Use a service provider to bind site-specific configurations or services based on the domain.
Here's a basic example to get you started:
-
Create Middleware: Generate a middleware to handle domain-specific logic.
php artisan make:middleware DomainMiddleware -
Middleware Logic: In the
handlemethod of your middleware, determine the domain and set configurations.namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use App\Models\Site; class DomainMiddleware { public function handle(Request $request, Closure $next) { $host = $request->getHost(); $site = Site::where('domain', $host)->first(); if (!$site) { abort(404, 'Site not found'); } // Set site-specific configurations config(['app.site' => $site]); return $next($request); } } -
Register Middleware: Register your middleware in
app/Http/Kernel.php.protected $middlewareGroups = [ 'web' => [ // Other middleware \App\Http\Middleware\DomainMiddleware::class, ], ]; -
Routing: Use routes to handle requests. You can use the domain information from the middleware to load different views or controllers.
Route::get('/', function () { $site = config('app.site'); return view('welcome', ['site' => $site]); }); -
Database Table: Create a
sitestable to store domain-specific data.Schema::create('sites', function (Blueprint $table) { $table->id(); $table->string('domain')->unique(); $table->string('name'); $table->timestamps(); }); -
Service Provider: Optionally, create a service provider to bind services or configurations based on the domain.
This setup allows you to handle multiple domains with a single Laravel application, similar to Django's sites framework. You can expand this by adding more domain-specific logic, such as loading different themes, configurations, or content.