Video Version of the Lesson
[Only for premium members]
[Only for premium members]
[Only for premium members]
We start our course with a simple version of multi-tenancy: records restricted by users assigned to them, so users would see only their records.
Some people don't even consider it a "multi-tenancy", meaning records should be restricted not by a user, but by company or team, using sub-domains, multi-databases, or something more complex.
But, in a broader sense, multi-tenancy means dividing your data by some tenant, however you define that tenant in your project. So, as the most simple example, we will divide the data of Project
and Task
Eloquent models by projects.user_id
and tasks.user_id
fields, in the same database.
I have made a simple demo project with two Models: Task
and Project
with CRUDs for both of them. Also, I added a relation: Task
-> belongsTo -> Project
.
In this section of the course, we will cover how to create a user_id
field and filter by that so every user would see only their projects and tasks.
First, we must add a user_id
column to the projects
table.
php artisan make:migration "add user id to projects table"
database/migrations/xxx_add_user_id_to_projects_table.php:
Schema::table('projects', function (Blueprint $table) { $table->foreignId('user_id')->constrained()->cascadeOnDelete(); });
We also added the user_id
to the Project
model in the fillable. I prefer to have all the fields fillable except for id
and timestamps
.
app/Models/Project.php:
class Project extends Model{ protected $fillable = [ 'name', 'user_id', ];}
Now, our goal is to add user_id
value to the projects automatically, from the logged-in user. And we have three options here.
In the store()
method of the ProjectController
, we create...