Courses

Laravel 12 Multi-Tenancy: All You Need To Know

archtechx / tenancy: Filter Records and Protect Subdomains

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Adding tenant_id to projects table
- Using BelongsToTenant trait for automatic filtering
- Implementing BelongsToPrimaryModel for related models
- Adding subdomain access protection middleware

Link to the repository

[Only for premium members]

In the second part of reviewing tenancy for Laravel for a single database, let's add the tenant_id to the projects table, and I will show you what this package does brilliantly to filter the records.

database/migrations/xxx_add_tenant_id_to_projects_table.php:

Schema::table('projects', function (Blueprint $table) {
$table->foreignId('tenant_id')->constrained();
});

app/Models/Project.php:

class Project extends Model
{
protected $fillable = [
'name',
'tenant_id',
];
}

Filter Records

In the previous lessons of this course, we added global scopes or traits to fill tenant_id automatically and then filtered by that. So, this package does that for us.

In the documentation section of single database tenancy, you may find an example saying to add the BelongsToTenant trait on a primary Model, and all the tenant logic will happen automatically. It will assume this Model has a tenant_id field, which will be filled in automatically.

app/Models/Project.php:

use Stancl\Tenancy\Database\Concerns\BelongsToTenant;
 
class Project extends Model
{
use BelongsToTenant;
 
protected $fillable = [
'name',
'tenant_id',
];
}

But what if we need to get tasks? We don't have the tenant_id field in the tasks table. For such a case, we must...

The full lesson is only for Premium Members.
Want to access all 22 lessons of this course? (88 min read)

You also get:

  • 76 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord