2

I'm trying to build a search functionality in my laravel app. I want to search on the name of a tag that is related with a pivot table to my loops. But I get the error 'undefined variable : query'

This is my controller method :

public function search($query) {

    $searchResult = Loop::whereHas('tags', function ($q) {
                $q->where('name', 'LIKE', '%'. $query .'%');  
            })->get(); 

    return Response::json($searchResult);
}
Jim Peeters
  • 2,573
  • 9
  • 31
  • 53
  • Possible duplicate of [php variables in anonymous functions](http://stackoverflow.com/questions/11420520/php-variables-in-anonymous-functions) – Fabio Antunes May 10 '16 at 08:56

1 Answers1

4

You should pass $query variable into a closure with use(), like this:

$searchResult = Loop::whereHas('tags', function ($q) use ($query) {
            $q->where('name', 'LIKE', '%'. $query .'%');  
        })->get(); 

http://php.net/manual/en/functions.anonymous.php (check example #3)

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279