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...
What is personal preference based on? What makes one better than the other?
The advantage of having it in model is it's really easy to follow the flow.
Observer it's much harder to follow the application flow but if you have a ton of code you can argue maybe observer would be better in complex apps.
I personally don't like obeaervers due to it making much harder to track the application flow. So there should be a really good reason for using it. Like maybe it's in a app that's heavily event based and lots of steps get fired when user is created.