1

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.

Sushant Aryal
  • 3,125
  • 1
  • 25
  • 22
  • 1
    As php says "Undefined variable user_id" that is the problem. meaning $q->where('user_id', '=', $user_id); at this line there is no variable named $user_id . I guess you need to pass $user_id variable inside your lambda function. – Madcoe Dec 04 '14 at 06:57
  • I am passing the $user_id variable. I checked it by printing the variable. – Sushant Aryal Dec 04 '14 at 08:11
  • Im talking about if variable exists inside lambda function inside function($q) { } because it is a different function therefore a different scope. Please check http://php.net/manual/en/language.variables.scope.php here for more information about scopes in php. – Madcoe Dec 04 '14 at 08:15
  • 1
    For a specific solution to your problem please check http://stackoverflow.com/questions/11420520/php-variables-in-anonymous-functions – Madcoe Dec 04 '14 at 08:23

0 Answers0