Passing conditional param to Eager Loading in lara

2020-05-03 11:51发布

问题:

my code is as followed:

   return User::whereHas('roles', function ($role, $query) {
            return $role;
            $query->whereId($role);
        })->get();

what I am trying is to pass role id here to query builder.

it ends up with following error:

Symfony\Component\Debug\Exception\FatalThrowableError
Too few arguments to function App\Http\Controllers\UserController::App\Http\Controllers\{closure}(), 1 passed in /Users/x/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 962 and exactly 2 expected 

回答1:

I think this is what you want:

A closure is a function that is evaluated in its own environment, which has one or more bound variables that can be accessed when the function is called.

The use() keyword let's you import variables from outside the function environment, inside the function.

return User::whereHas('roles', function ($query) use ($role) {
    return $query->whereId($role);
})->get();