Search code examples
phplaravel-5.3laravel-query-builder

Laravel query builder not using variable from get method


I have this function in one of my controller.

public function tourList($country, $category)
{
    $tour = Tour::whereHas('country', function($q) {
                    $q->where('name','=', $country);
                })
                ->whereHas('category', function($r) {
                    $r->where('name','=', $category);
                })
                ->get();

    return view('tour-list.blade.php')->withTour('$tour');
}

Though have passed two variables from get method. But i am getting error of

Undefined variable: country

Solution

  • You are missing use in anonymous function so your query willl be as:

    $tour = Tour::whereHas('country', function($q) use($country) {
                    $q->where('name','=', $country);
                })
                ->whereHas('category', function($r) use($category) {
                    $r->where('name','=', $category);
                })
                ->get();
    

    Docs