2016-11-06 4 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 ]); 

} 

が、それは、このエラーにItemsController.phpライン192で

ErrorException私をスロー:あなたは '$要求' 変数がある見ることができるように 要求

:未定義の変数を

public function search_tag(Request $request){ 

しかし、なぜそれが私に「requ est '変数は定義されていませんか?任意のアイデア、助けてください?

答えて

2

閉鎖あなたが利用できない$要求を使用しているので、あなたが閉鎖に$request変数を渡し使用方法

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

経由$要求を渡す必要があります:

where(function($query) use ($request) { 

クロージャは、親スコープから変数を継承することもできます。そのような変数はすべてuse言語構造に渡さなければなりません。

http://php.net/manual/en/functions.anonymous.php

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(); 
関連する問題