laravelget-requestundefined-variable

Laravel - Undefined variable: request


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

When dd($request->sty); equal 3

however I put $request->sty in the whereHas is

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

Solution

  • Try this

    If you want to use any variable inside the where closure then you have to pass that variable inside the 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();
    }