我创建了一个函数
public function searchFile(Request $request)
{
$this->validate($request,[
'text' => 'required'
]);
$data['site_title'] = $this->site_title;
$data['page_title'] = 'File Search';
$data['category'] = Category::all();
$data['menu_cat'] = Category::take(6)->get();
$data['subcategory'] = SubCategory::orderBy('name','ASC')->get();
$data['title'] = 0;
$data['files'] = File::where('title','like',"%$request->text%")->orderBy('download','DESC')->paginate(12);
$data['general'] = GeneralSetting::first();
return view('home.search-file',$data);
}
目前,它会搜索表格中的所有可用类别
如何修改以搜索与一个类别相关的内容?
我可以在其中使用“if”
如果打开类别16,则仅在此类别中搜索
答案 0 :(得分:0)
您必须将category_id传递给您的请求,然后您可以执行以下操作:
$data['category'] = $request->has('category_id') ? Category::find($request->input('category_id')) : Category::all();
或者在Laravel 5.5+中,使用$ request-> filled()代替$ request-> has()($ request-> has()返回true,即使category_id也是如此== null)
$data['category'] = $request->filled('category_id') ? Category::find($request->input('category_id')) : Category::all();
我们在这里使用三元而不是if / else结构。在if / else中它会是:
if ($request->filled('category_id'))
$data['category'] = Category::find($request->input('category_id'));
else
$data['category'] = Category::all();