1. Go to this page and download the library: Download rylxes/laravel-multitenancy library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
rylxes / laravel-multitenancy example snippets
Schema::table('projects', function (Blueprint $table) {
$table->foreignId('tenant_id')->constrained()->index();
});
use Illuminate\Database\Eloquent\Model;
use Rylxes\Multitenancy\Concerns\BelongsToTenant;
class Project extends Model
{
use BelongsToTenant;
}
// routes/web.php or bootstrap/app.php
Route::middleware('tenancy')->group(function () {
Route::resource('projects', ProjectController::class);
});
use Rylxes\Multitenancy\Concerns\BelongsToTenant;
class Invoice extends Model
{
use BelongsToTenant;
}
// Automatically adds WHERE tenant_id = ? to all queries
$invoices = Invoice::all(); // Only current tenant's invoices
// tenant_id auto-filled on create
$invoice = Invoice::create(['amount' => 100]); // tenant_id set automatically
// Without any tenant context active:
Invoice::all(); // Throws NoCurrentTenantException
// Get all invoices across all tenants (admin use)
$allInvoices = Invoice::withoutTenantScope()->get();
use Rylxes\Multitenancy\Facades\Tenant;
// Set current tenant
$tenant = \Rylxes\Multitenancy\Models\Tenant::find(1);
Tenant::makeCurrent($tenant);
// Check current tenant
Tenant::current(); // Returns Tenant model or null
Tenant::check(); // Returns bool
// Run code as a specific tenant
Tenant::execute($tenant, function () {
// All queries scoped to $tenant here
$projects = Project::all();
});
// Previous tenant context (or none) is restored after
// Global helper
tenant(); // Returns current Tenant or null
// Forget current tenant
Tenant::forgetCurrent();
use Rylxes\Multitenancy\Testing\ActingAsTenant;
class ProjectTest extends TestCase
{
use ActingAsTenant;
public function test_projects_are_scoped_to_tenant(): void
{
$tenant = Tenant::create(['name' => 'Test']);
$this->actingAsTenant($tenant);
$project = Project::create(['name' => 'My Project']);
$this->assertEquals($tenant->id, $project->tenant_id);
}
}