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
Thank you for the course. Especially for pointing out which option is slower / faster. Useful.