Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Filter Multiple Models: With Traits or Relationships

Premium
4:09

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 of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

P
Pēteris ✓ Link copied!

Thank you for the course. Especially for pointing out which option is slower / faster. Useful.

J
johnogle ✓ Link copied!

Great course, so far! Thanks, Povilas. I think there is a small typo though at the end of Option 1. You state:

The global scope won't work, and all the projects will not be shown.

I think you mean " all the projects will be shown".

M
Modestas ✓ Link copied!

Thank you for letting us know! It should be fixed now!

M
muuucho ✓ Link copied!

If you run into ambigous problems using Traits with global scope above, change this:

	static::addGlobalScope(function (Builder $builder) {
							$builder->where('user_id', auth()->id());
	});

to qualifiing the column

	static::addGlobalScope('active', function (Builder $query) {
            $query->where($query->qualifyColumn('user_id'), '=', auth()->id());
        });
You can read more [here:](https://github.com/tylernathanreed/laravel-relation-joins/issues/18)