想象一下,我们有一些像这样的查询字符串:
example.com/posts?param1=val1¶m2=val2¶m3=val3..
我正在使用以下脚本,但我知道这不是标准和最好的方式,实际上它是我见过/做过的最糟糕的!
$data = [
'files' => File::orderBy('id','desc')->paginate(12),
];
//Adding query strings
if (!empty($request->search)) {
$replacement_data = [
'files' => File::where('name','LIKE',"%$request->search%")->paginate(12),
];
return view ("manage.Files.index")->withData(array_replace($data,$replacement_data));
}
else {
return view ("manage.Files.index")->withData($data);
}
现在我的问题很清楚,如何在SQL / Eloquent where语句中使用这些查询字符串作为过滤器?
答案 0 :(得分:2)
您可以动态生成查询。我在项目中的方式是依赖注入Model类。
private $model;
public function __construct(File $model)
{
$this->model = $model;
}
public function search(Request $request) {
$query = $this->model;
// add query string to limit search or ..
if (!empty($request->search)) {
$query = $query->where('name','LIKE',"%$request->search%");
}
$data['files'] = $query->orderBy('id','desc')->paginate(12);
return view ("manage.Files.index")->withData($data);
}