What is Multi Tenancy?

The term “website or web-application multi tenancy” means a single instance of website or application runs on a server and serves multiple tenants. like same application host in multiple sub domain.

Requirements :

Laravel 5.6 or above.
PHP 7.1 or up.
MySQL 5.7+, MariaDB 10.1.13+ or PostgreSQL 9+.
Optionally Apache 2.4+ or Nginx 1.12+.

Make sure you configure this user as your system connection in your database.php. Under connections:

'system' => [
    'driver' => 'mysql',
    'host' => env('TENANCY_HOST', '127.0.0.1'),
    'port' => env('TENANCY_PORT', '3306'),
    'database' => env('TENANCY_DATABASE', 'tenancy'),
    'username' => env('TENANCY_USERNAME', 'tenancy'),
    'password' => env('TENANCY_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,
]

Install Package

composer require "hyn/multi-tenant:5.3.*"

php artisan vendor:publish --tag=tenancy

php artisan migrate --database=system

Change system to your system connection name.

Create Tenant and switch to newly created tenant

   $website = new Website;
  // Implement custom random hash using Laravels Str::random
   $website->uuid = Str::random(10);
   app(WebsiteRepository::class)->create($website);
    
  //dd($website->uuid); // Random string of length 10
    $subdomain=$request->subdomain_name.'.maindomain.com';
    $hostname = new Hostname;
    $hostname->fqdn = $subdomain;
    $hostname = app(HostnameRepository::class)->create($hostname);
    app(HostnameRepository::class)->attach($hostname, $website);

   //   dd($website->hostnames); // Collection with $hostname

    $tenancy = app(Environment::class);

    $tenancy->hostname($hostname);

    $tenancy->hostname(); // resolves $hostname as currently active hostname

    $tenancy->tenant($website); // switches the tenant and reconfigures the app

    $tenancy->website(); // resolves $website
    $tenancy->tenant(); // resolves $website

    $tenancy->identifyHostname(); // resets resolving $hostname by using the Request

Database migration for multi tenant

Run command in cmd prompt for import newly created table ‘php artisan tenancy:migrate‘.