Search code examples
phplaravellaravel-5saasmultisite

Laravel 5 one instance, multiple identical subdomains


I would like to use one server that uses a base Laravel installation, and have subdomains that reference that installation. All the subdomains will be the same like an SaaS.

I've looked around and the databases connections are easy, but I'm wondering if you can do this intelligently with the same codebase for subdomains.

The subdomains world include the minimal needed files for its subdomain -- perhaps, the public index and bootstrap? Hopefully without symlinking everything.

I'm not worried about the server configuration, I just would like to be pointed in the right direction for Laravel code, like middleware to handle the request then point to that subdomain?

A lot of threads I've read don't have an answer that seems standard, any ideas or links?

Also, if it were a multi server setup wouldn't one be OK with an NFS server for the core?


Solution

  • With laravel you can check the URL without using subdomains but just group routing requests.

    Route groups may also be used to handle sub-domain routing. Sub-domains may be assigned route parameters just like route URIs, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the domain key on the group attribute array:

    Route::group(['domain' => '{account}.myapp.com'], function () {
        Route::get('user/{id}', function ($account, $id) {
            // your code
        });
    });
    

    Read more about this on laravel documentation https://laravel.com/docs/5.4/routing#route-group-sub-domain-routing


    BOUNTY

    You can also supply more parameters to the same Route::group, that could be, for example

    Route::group(['domain' => '{subdomain}.{domain}.{tld}'], function () {
        Route::get('user/{id}', function ($account, $id) {
            // your code
        });
    });
    

    In the same time, you can decide to limit the domain parameters you are going to accept using the Route::pattern definition.

    Route::pattern('subdomain', '(dev|www)');
    Route::pattern('domain', '(example)');
    Route::pattern('tld', '(com|net|org)');
    Route::group(['domain' => '{subdomain}.{domain}'], function () {
        Route::get('user/{id}', function ($account, $id) {
            // your code
        });
    });
    

    In this previous example, all the following domains will be accepted and correctly routed

    • www.example.com
    • www.example.org
    • www.example.net
    • dev.example.com
    • dev.example.org
    • dev.example.net