2016-11-06 89 views
1

我正在嘗試做一些類似於自動建議的操作,請參閱下面的代碼。返回'未定義變量'即使變量存在

//search suggestion base on the string criteria given 
public function search_tag(Request $request){ 
    $tags = tags::where(function($query){ 
     foreach(item_tags::where('item_id',$request->item_id)->get() as $i){ //this is the line 192 
      $query->orWhere('tag_id','!=',$i->tag_id); 
     } 
    })->where('tag_name','LIKE','%'.$request->ss.'%')->get(); 

    return response()->json([ 'success' => true, 'tags' => $tags, 'ss' => $request->ss ]); 

} 

但將我這個錯誤

ErrorException在ItemsController.php行192:未定義的變量: 要求

正如你可以看到有一個 '$請求' 變量

public function search_tag(Request $request){ 

但爲什麼它告訴我'必需est'變量未定義?任何想法,請幫助嗎?

回答

2

其中關閉你正在使用$請求這是不可用,所以你需要通過使用方法

public function search_tag(Request $request){ 
    $tags = tags::where(function($query) use ($request) { 
     foreach(item_tags::where('item_id',$request->item_id)->get() as $i){ //this is the line 192 
      $query->orWhere('tag_id','!=',$i->tag_id); 
     } 
    })->where('tag_name','LIKE','%'.$request->ss.'%')->get(); 

    return response()->json([ 'success' => true, 'tags' => $tags, 'ss' => $request->ss ]); 

} 
1

這是一個封閉且請求沒有在此範圍內已知的,嘗試以下操作:

//search suggestion base on the string criteria given 
    public function search_tag(Request $request) use ($request){ 
     $tags = tags::where(function($query) use { 
      foreach(item_tags::where('item_id',$request->item_id)->get() as $i){ //this is the line 192 
       $query->orWhere('tag_id','!=',$i->tag_id); 
      } 
     })->where('tag_name','LIKE','%'.$request->ss.'%')->get(); 

     return response()->json([ 'success' => true, 'tags' => $tags, 'ss' => $request->ss ]); 

} 
1

在關閉,如果你想使用變量,那麼你必須使用內寫( )。

$tags = tags::where(function($query) use ($request){ 
    foreach(item_tags::where('item_id',$request->item_id)->get() as $i){ //this is the line 192 
     $query->orWhere('tag_id','!=',$i->tag_id); 
    } 
})->where('tag_name','LIKE','%'.$request->ss.'%')->get();