未定义的变量:sub方法中的请求

时间:2017-12-01 13:00:52

标签: php laravel laravel-5

当我尝试获取与category表有关系的所有记录时,category_definition_id是搜索输入,我无法访问sub方法中的$ request-> category变量。它在Laravel 5.5中。有什么想法吗?

public function jobopenings(Request $request)
{
  $category_definitions = Category_definition::all();
  $skill_definitions = Skill_definition::all();

  $ads = new Ad;

  // Search for a user based on their name.
  if ($request->has('category')) {

    $ads = $ads->whereHas('categories', function($query){
        $query->where('category_definition_id', $request->category);
      });
  }

  $ads = $ads->where('type','1')->orderBy('created_at','desc')->paginate(15);

    return View::make('jobs')
    ->with('ads', $ads)
    ->with('category_definitions',$category_definitions)
    ->with('skill_definitions', $skill_definitions)
    ->with('ad_type','1');
}

2 个答案:

答案 0 :(得分:1)

您必须使用use($request)声明它:

$ads = $ads->whereHas('categories', function($query) use ($request) {
           $query->where('category_definition_id', $request->category);
       });

答案 1 :(得分:0)

添加use子句:

$ads = $ads->whereHas('categories', function($query) use ($request) {
        $query->where('category_definition_id', $request->category);
    });
}