How to handle multi-tenancy in Laravel and ReactJS applications



Image not found!!

Handling multi-tenancy in a Laravel and ReactJS application involves managing data isolation, user authentication, and routing based on the tenant context. Here's a step-by-step guide on how to achieve multi-tenancy in such an application:

Laravel Backend:

1. Database Configuration:

  • Use a separate database schema or a prefix for each tenant. You can configure this in your database configuration file (config/database.php).
php
'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => 'tenant_', 'strict' => true, 'engine' => null, ],

2. Middleware:

  • Create a middleware to identify the tenant based on the request (e.g., subdomain, domain, or header).
  • Switch the database connection based on the identified tenant.
php
// Example Middleware public function handle($request, Closure $next) { $tenant = $this->identifyTenant($request); // Switch database connection config(['database.connections.mysql.database' => 'tenant_' . $tenant]); DB::reconnect('mysql'); return $next($request); }

3. Tenant Identification:

  • Identify the tenant from the request (subdomain, domain, or header).
  • You can use a middleware or global scope for this.
php
public function identifyTenant($request) { // Implement logic to identify tenant (e.g., subdomain) return $tenant; }

4. User Authentication:

  • Ensure that user authentication is scoped to the current tenant.
php
// Modify User model public function scopeTenant($query) { return $query->where('tenant_id', auth()->user()->tenant_id); }

ReactJS Frontend:

1. Store Tenant Information:

  • When the user logs in, store the tenant information (e.g., ID) in the client-side storage (localStorage or sessionStorage).

2. API Requests:

  • Attach the tenant information to each API request.
  • You may include the tenant ID in the headers of your requests.
javascript
// Example using Axios axios.defaults.headers.common['X-Tenant-ID'] = localStorage.getItem('tenant_id');

3. Routing:

  • Handle routing based on the tenant context.
  • Redirect users to the appropriate routes based on their tenant.
javascript
// React Router Example const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={(props) => isLoggedIn() && isAuthorized() ? ( <Component {...props} /> ) : ( <Redirect to={`/login?redirect=${props.location.pathname}`} /> ) } /> );

Additional Considerations:

  1. Tenant Switching:

    • Implement a mechanism to allow users (e.g., administrators) to switch between tenants.
  2. Global Scopes:

    • Use Laravel's global scopes to automatically filter queries by the current tenant.
  3. Testing:

    • Create automated tests for each tenant to ensure data isolation.
  4. Security:

    • Ensure that tenant-specific data is properly secured and isolated.

By following these steps, you can implement multi-tenancy in a Laravel and ReactJS application, providing a scalable and secure solution for serving multiple tenants.