'eager loading pass variable in withCount where condition

$user = 1;
                       
Forum::with(['posts' => function($query){
    $query->withCount(['comments => function($query){
            $query->where('id_user', $user); 
        }]);
}])
->get();

How to pass the value of the $user variable to $query->where('id_user', $user);

$user is not working (appears underlined in red in the editor).



Solution 1:[1]

$user = 1;
                       
Forum::with(['posts' => function($query) use ($user){
    $query->withCount(['comments => function($query) use ($user){
            $query->where('id_user', $user); 
        }]);
}])
->get();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JEJ