Published on September 23 Apr 25

Installing Laravel 11 and Setting Up Multitenancy

3 weeks ago 129

Setting Up Multitenancy in Laravel 11: A Step-by-Step Guide

Laravel is one of the most popular PHP frameworks, renowned for its elegant syntax and robust features. Laravel 11 builds on this legacy, introducing enhanced capabilities. One advanced use case for Laravel is creating a multitenant application, where multiple tenants (clients) share the same application while keeping their data isolated.

This guide walks you through installing Laravel 11 and setting up multitenancy using the spatie/laravel-multitenancy package.


Prerequisites

Before starting, ensure you have the following installed:

  • PHP: 8.1 or higher

  • Composer: Dependency manager for PHP

  • Web Server: Apache, Nginx, or similar

  • Database: MySQL or another supported database


Step 1: Installing Laravel 11

  1. Open your terminal and create a new Laravel project:

    composer create-project --prefer-dist laravel/laravel blog
    

    This creates a Laravel project in a directory named blog.

  2. Navigate to the project directory:

    cd blog
    
  3. Set permissions for the storage and bootstrap/cache directories:

    chmod -R 775 storage
    chmod -R 775 bootstrap/cache
    


Step 2: Configuring Your Environment

  1. Copy the example environment file:

    cp .env.example .env
    
  2. Open the .env file and update the database credentials:

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=your_database_name
    DB_USERNAME=your_database_user
    DB_PASSWORD=your_database_password
    
  3. Generate a new application key:

    php artisan key:generate
    


Step 3: Setting Up Multitenancy

Laravel provides a solid foundation for multitenancy. The spatie/laravel-multitenancy package is recommended for Laravel 11 due to its active maintenance and robust features.

3.1 Install the Spatie Multitenancy Package

Install the package via Composer:

composer require spatie/laravel-multitenancy

3.2 Publish the Configuration File

Publish the package's configuration file:

php artisan vendor:publish --provider="Spatie\Multitenancy\MultitenancyServiceProvider"

3.3 Configure the Multitenancy Package

Open config/multitenancy.php and adjust the settings. Below is a basic configuration:

return [
    'tenant_finder' => Spatie\Multitenancy\TenantFinder\DomainTenantFinder::class,
    'current_tenant_container_key' => 'currentTenant',
    'switch_tenant_tasks' => [
        Spatie\Multitenancy\Tasks\SwitchTenantDatabaseTask::class,
    ],
    'tenant_artisan_search_fields' => [
        'id',
    ],
    'tenant_model' => App\Models\Tenant::class,
    'landlord_database_connection_name' => env('LANDLORD_DB_CONNECTION', 'mysql'),
    'queues_are_tenant_aware_by_default' => true,
];

3.4 Create the Tenant Model and Migration

Generate a Tenant model with a migration:

php artisan make:model Tenant -m

Open the migration file in database/migrations and define the tenant fields:

public function up()
{
    Schema::create('tenants', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('domain')->unique();
        $table->timestamps();
    });
}

Run the migration:

php artisan migrate

3.5 Implement Tenant Switching

Update the Tenant model to extend the Spatie Tenant class:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\Multitenancy\Models\Tenant as BaseTenant;

class Tenant extends BaseTenant
{
    //
}

In AppServiceProvider or a custom service provider, configure tenant identification and switching:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Spatie\Multitenancy\Models\Tenant;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Tenant::current()->each(function ($tenant) {
            $tenant->makeCurrent();
        });
    }

    public function register()
    {
        //
    }
}


Step 4: Testing Your Multitenant Application

To test the setup:

  1. Manually add tenants to the tenants table:

    INSERT INTO tenants (name, domain, created_at, updated_at) VALUES
    ('Tenant 1', 'tenant1.localhost', NOW(), NOW()),
    ('Tenant 2', 'tenant2.localhost', NOW(), NOW());
    
  2. Update your /etc/hosts file to map the domains to your local server:

    127.0.0.1 tenant1.localhost
    127.0.0.1 tenant2.localhost
    
  3. Visit tenant1.localhost or tenant2.localhost in your browser. The application should switch context based on the domain.


Conclusion

Setting up multitenancy in Laravel 11 enhances your application's ability to serve multiple clients efficiently. The spatie/laravel-multitenancy package simplifies the process, making it accessible and robust. By following this guide, you’re well-equipped to build a scalable multitenant application with Laravel 11.

Happy coding!