title: Multi-tenant sub-domains in Laravel 5
body: <p>I am building a SaaS app in Laravel and want to give each person/company their own sub-domain. I have a <code>users</code> table with a <code>company_id</code> column. I have a <code>companies</code> table with a <code>sub_domain</code> column, which will be the sub-domain for that company. I don't want Company A to be able to visit Company B's sub-domain.</p>
  
  <p>I have looked a quite a few articles and many forums on how to handle this and I am not finding any solutions that work. I am thinking that I need to use Middleware in combination with route grouping, but I just can't figure it out. Does anyone have experience with this?</p>
  
  <p>Here is my <code>routes.php</code>:</p>
  
  <pre><code>Route::group(['domain' =&gt; '{sub_domain}.' . env('APP_DOMAIN_NAME'), 'middleware' =&gt; 'subdomain'], function() {
  
      Route::auth();
  
      Route::group(['middleware' =&gt; 'guest'], function () {
          //Route::get('/', 'PublicController@index');
          Route::get('/tickets/create', 'TicketsController@create');
          Route::post('/tickets/create', 'TicketsController@store');
      });
  
      Route::group(['middleware' =&gt; 'auth'], function () {
          Route::get('/tickets', 'TicketsController@index');
          Route::get('/tickets/{id}', 'TicketsController@edit');
          Route::patch('/tickets/{id}', 'TicketsController@update');
          Route::delete('/tickets/{id}', 'TicketsController@destroy');
          Route::get('/my-tickets', 'TicketsController@myTickets');
          Route::get('/tickets/close/{id}', 'TicketsController@closeTicket');
  
      });
  });
  </code></pre>
  
  <p>The problem with this is that I can visit another sub-domain successfully. Now, I can still only view the tickets that are associated with the currently logged in user's company. I would like to throw a 403, or even just redirect back to their own sub-domain.</p>
  
  <p>Here is the <code>Subdomain.php</code> middleware:</p>
  
  <pre><code>public function handle($request, Closure $next)
  {
      $request_uri = $request-&gt;server('HTTP_HOST');
      $this-&gt;checkSubdomainExists($request_uri);
  
      if(Auth::check()) {
          $user = User::find(Auth::user()-&gt;id);
          if($user-&gt;company-&gt;sub_domain !== Session::get('company_sub_domain')) {
              Session::forget('company_sub_domain');
              return 'not Authed';
          }
      }
  
      return $next($request);
  }
  </code></pre>