Laravel - 未定义变量:请求

Laravel - Undefined variable: request

我的http://localhost:8888/VGL/public/category/18?sty=3

dd($request->sty);等于3

不过我把$request->sty放在whereHas里面是

Undefined variable: request

public function show(Request $request, $id)
{
    $products = Product::with('features')
        ->whereHas('features', function ($q) {
            return $q->where('id', $request->sty);
        })
        ->where('category_id',17)
        ->get();
}

试试这个

如果您想在 where closure 中使用任何变量,则必须在 use($variable)

中传递该变量
public function show(Request $request, $id)
{
    $products = Product::with('features')
        ->whereHas('features', function ($q) use($request) {
            return $q->where('id', $request->sty);
        })
        ->where('category_id',17)
        ->get();
}