Passing conditional param to Eager Loading in larave ends with error

試著忘記壹切 提交于 2020-01-22 02:34:08

问题


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();


来源:https://stackoverflow.com/questions/58929707/passing-conditional-param-to-eager-loading-in-larave-ends-with-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!