DatsunBing
DatsunBing

Reputation: 9076

Laravel: Choose different controllers for each request host

I have a Laravel application that needs to service multiple domains, for example, firstdomain.com, seconddomain.com, thirddomain.com. The logic layer stays the same irrespective of the domain name, but the presentation changes. Therefore, I want to call a different set of controllers for each domain. How can I do this?

I have created a middleware that gets the value of $_SERVER['HTTP_HOST'] and sets it as an attribute on the request object, but I'm not sure where to go from there. Ideally I would set it as a namespace prefix for a group of controllers.

Upvotes: 0

Views: 473

Answers (1)

Cyril Graze
Cyril Graze

Reputation: 3890

You can group your controllers in groups where their domain implementations diverge. You may also have common controllers shared:

// Common route
Route::get('about', 'ContentController@about');

// Diverge by domain
Route::group(['domain' => 'foodomain.com'], function () {
    Route::resource('task', 'FooTaskController');
});

Route::group(['domain' => 'bardomain.com'], function () {
    Route::resource('task', 'BarTaskController');    
});

Route::group(['domain' => 'loldomain.com'], function () {
    Route::resource('task', 'LolTaskController');
});

You could also have these controllers inherit from a common parent Controller class, where any shared logic would go

<?php

namespace App\Http\Controllers;

class FooTaskController extends TaskController

(...)

class BarTaskController extends TaskController

(etc...)

Your views can also be organized by domain:

\app
\bootstrap
\resources
    \assets
    \lang
    \views
        \foo
            task.blade.php
            home.blade.php
        \bar
            task.blade.php
            home.blade.php
        \lol
            task.blade.php
            home.blade.php

Upvotes: 2

Related Questions