Code Demon Code Demon - 1 month ago 11
PHP Question

returns 'undefined variable' even the variable is exist

I'm trying to do something like a auto suggestion, see below codes.

//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 ]);

}


but it throws me this error


ErrorException in ItemsController.php line 192: Undefined variable:
request


As you can see there is a '$request' variable

public function search_tag(Request $request){


but why it tells me that 'request' variable is undefined? any ideas, help please?

Answer

In where closure you're using $request which is not available, so you need to pass $request via use method

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 ]);

}