Courses

Laravel 12 Multi-Tenancy: All You Need To Know

Filter Multiple Models: With Traits or Relationships

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Creating a trait for code reusability
- Implementing relationship-based filtering
- Performance considerations between direct and relationship filtering
- Limitation of Global Scope with DB::table queries

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

Now, let's add the same user_id to another model: Tasks. We will use two approaches to filter the tasks.

First, as I mentioned, we have the project_id column. So we have project_id in the tasks table, but I also added the user_id.

database/migrations/xxx_add_user_id_to_tasks_table.php:

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

So, it's your choice whether to save user_id in all tables or to use a "higher" relationship with project_id: it will be slower to query but a smaller table without the user ID. We will see both approaches.


Option 1. Filter by User with Traits.

In the same way, as we did with the projects, we can add the anonymous global scope to the Task Model.

app/Models/Task.php:

use Illuminate\Database\Eloquent\Builder;
 
class Task extends Model
{
protected $fillable = [
'name',
'project_id',
];
 
protected static function booted(): void
{
static::creating(function (Task $task) {
$task->user_id = auth()->id();
});
 
static::addGlobalScope(function (Builder $builder) {
$builder->where('user_id', auth()->id());
});
}
 
// ...
}

We can check if everything works by creating

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:

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