I am having an issue regarding Eager Loading with constraints. I have a method that returns all projects.
public function findProjectById($id, $user_id)
{
$project = Project::with([
'tasklists' => function($query) {
$query->with(['tasks' => function($q) {
$q->with(['subtasks', 'comments' => function($com) {
$com->with('user');
}]);
}])
->with('project');
}
])->findOrFail($id);
return $project;
}
This works fine. But i want to return only those projects where a task belongs to a current user. There is a field in tasks table for user(user_id). For that i used a where query inside tasks.
$query->with(['tasks' => function($q) {
$q->where('user_id', '=', $user_id);
$q->with(['subtasks', 'comments' => function($com) {
$com->with('user');
}]);
}])
But it throws Error Exception "Undefined variable user_id"
"type":"ErrorException","message":"Undefined variable: user_id"
Can anyone point out what seems to be the problem. Thanks.