returns 'undefined variable' 即使变量存在

returns 'undefined variable' even the variable is exist

我正在尝试做一些类似自动建议的事情,请参阅下面的代码。

//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 in ItemsController.php line 192: Undefined variable: request

如您所见,有一个“$request”变量

public function search_tag(Request $request){

但为什么它告诉我 'request' 变量未定义?有什么想法,请帮忙?

where 闭包中,您使用的 $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 ]);

}

$request 变量传递到闭包中:

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

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.

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

这是一个闭包,请求在此范围内未知,请尝试以下操作:

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

}

在闭包中如果你想使用变量那么你必须在use()中写。

$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();