即使变量存在,也返回'undefined variable'

时间:2016-11-06 09:30:31

标签: php laravel eloquent laravel-5.3

我正在尝试执行类似自动建议的操作,请参阅下面的代码。

//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中的ErrorException第192行:未定义的变量:   请求

正如您所看到的,有一个'$ request'变量

public function search_tag(Request $request){

但为什么它告诉我“请求”变量未定义?任何想法,请帮忙吗?

4 个答案:

答案 0 :(得分:2)

关闭时,您使用的 $ request 不可用,因此您需要通过 $ 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 :(得分:1)

$request变量传递给闭包:

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

闭包还可以从父作用域继承变量。任何此类变量都必须传递给use语言构造。

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

答案 2 :(得分: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 ]);

}

答案 3 :(得分:1)

如果你想使用变量,那么你必须在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();