Courses

Laravel 12 Multi-Tenancy: All You Need To Know

Setting user_id Column Automatically: Two Ways

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Adding user_id column to existing tables via migration
- Setting user_id automatically in Controller using auth()->id()
- Using Eloquent's creating event for universal user assignment

Video Version of the Lesson

[Only for premium members]

Link to the repository

[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.


Option 1. Controller.

In the store() method of the ProjectController, we create...

The full lesson is only for Premium Members.
Want to access all 21 video+text lessons of this course? (1 h 21 min)

You also get:

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