Laravel is one of the most popular PHP frameworks, known for its elegant syntax and robust features. Laravel 11 continues this tradition, offering even more features and improvements. One of the advanced use cases for Laravel is building a multitenant application, where multiple tenants (clients) share the same application but have their data separated.
In this guide, we’ll walk you through the process of installing Laravel 11 and setting up multitenancy.
Step 1: Prerequisites
Before you begin, make sure you have the following installed on your machine:
- PHP 8.1 or higher
- Composer
- A web server (e.g., Apache, Nginx)
- MySQL or another supported database
Step 2: Installing Laravel 11
First, open your terminal and run the following command to create a new Laravel project:
composer create-project --prefer-dist laravel/laravel blog
This will create a new Laravel project in a directory named blog
.
Navigate into your project directory:
cd blog
Next, set the appropriate permissions for the storage and bootstrap/cache directories:
chmod -R 775 storage
chmod -R 775 bootstrap/cache
Step 3: Configuring Your Environment
Copy the example environment file to create your own:
cp .env.example .env
Open the .env
file and update the following lines with your 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
Generate a new application key:
php artisan key:generate
Step 4: Setting Up Multitenancy
Laravel provides a great foundation for implementing multitenancy. One of the popular packages for handling multitenancy is hyn/multi-tenant
. However, as of Laravel 11, the spatie/laravel-multitenancy
package is a more recommended approach due to its active maintenance and comprehensive features.
Step 4.1: Install the Spatie Multitenancy Package
Run the following command to install the package:
composer require spatie/laravel-multitenancy
Step 4.2: Publish the Configuration File
Next, publish the package’s configuration file:
php artisan vendor:publish --provider="Spatie\Multitenancy\MultitenancyServiceProvider"
Step 4.3: Configure the Multitenancy Package
Open the config/multitenancy.php
file and adjust the configuration according to your needs. Here is a basic example:
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,
];
Step 4.4: Create the Tenant Model and Migration
Create a Tenant
model and a corresponding migration file:
php artisan make:model Tenant -m
Open the generated migration file in database/migrations
and define the necessary fields for your tenants. For example:
public function up()
{
Schema::create('tenants', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('domain')->unique();
$table->timestamps();
});
}
Run the migration to create the tenants
table:
php artisan migrate
Step 4.5: Implement Tenant Switching
To switch tenants based on the request, update the Tenant
model to implement Spatie\Multitenancy\Models\Tenant
:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Spatie\Multitenancy\Models\Tenant as BaseTenant;
class Tenant extends BaseTenant
{
//
}
Then, in your AppServiceProvider
or a dedicated service provider, you can configure how tenants are identified and switched:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Spatie\Multitenancy\Models\Concerns\UsesMultitenancyConfig;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Tenant::currentTenant()->each(function ($tenant) {
$tenant->makeCurrent();
});
}
public function register()
{
//
}
}
Step 5: Testing Your Multitenant Application
To test your multitenant setup, you can create a few tenants manually in the database and visit their respective domains to see if the application switches context correctly.
For example, add the following entries to your tenants
table:
INSERT INTO tenants (name, domain, created_at, updated_at) VALUES
('Tenant 1', 'tenant1.localhost', NOW(), NOW()),
('Tenant 2', 'tenant2.localhost', NOW(), NOW());
Add the domains to your hosts
file to point them to your local server:
127.0.0.1 tenant1.localhost
127.0.0.1 tenant2.localhost
Now, when you visit tenant1.localhost
or tenant2.localhost
in your browser, your application should switch context based on the domain.
Conclusion
Setting up multitenancy in Laravel 11 can significantly enhance your application’s ability to serve multiple clients efficiently. With the spatie/laravel-multitenancy
package, the process is streamlined and manageable. By following the steps outlined in this guide, you’ll be well on your way to creating a robust multitenant application with Laravel 11. Happy coding!