2016-05-10 27 views
2

我正在嘗試在我的laravel應用程序中構建搜索功能。我想搜索與透視表相關的標籤的名稱到我的循環。但我得到的錯誤'未定義的變量:查詢'爲什麼我不能在這個雄辯的數據庫調用方法中訪問我的變量?

這是我的控制器方法:

public function search($query) { 

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

    return Response::json($searchResult); 
} 
+0

可能重複的[anon中的php變量ymous函數](http://stackoverflow.com/questions/11420520/php-variables-in-anonymous-functions) –

回答

4

你應該通過$query可變進封閉與use(),像這樣:

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

http://php.net/manual/en/functions.anonymous.php(檢查示例#3)

+1

我正在尋找這樣的一段時間!我不能夠感謝你! –

+1

很高興能幫到你。 ) –

相關問題