我使用文本框和下拉菜单创建了一些搜索过滤器,所以当我点击搜索按钮时,我想使用这些过滤器来查询雄辩的关系。
搜索工作正常,我得到了正确的结果,但问题在于分页。当我点击下一页按钮(或任何其他页面)时,结果是结果,我再次获得所有内容。
我知道这是因为我在点击分页时没有做请求所以我的问题是我如何执行相同的查询但使用分页?
这是我的控制器功能
public function index(Request $request)
{
if(!empty($request)) {
$products = Product::with(['supplier', 'carrier', 'name']);
if($request->name) {
$products = $products->whereHas('Name', function ($query) use ($request) {
$products = $query->where('Name', $request->name);
});
}
if($request->subtype) {
$products = $products->whereHas('SubType', function ($query) use ($request) {
$products = $query->where('SubTypeId', $request->subtype);
});
}
if($request->supplier) {
$products = $products->whereHas('Supplier', function ($query) use ($request) {
$products = $query->where('SupplierId', $request->supplier);
});
}
if($request->carrier) {
$products = $products->whereHas('Carrier', function ($query) use ($request) {
$products = $query->where('CarrierId', $request->carrier);
});
}
$products = $products->paginate(8);
}
else {
$products = Product::with(['supplier', 'carrier', 'name'])->paginate(8);
}
$suppliers = Supplier::all();
$carriers = Carrier::all();
$subtypes = SubType::all();
$options = array(
'products' => $products,
'suppliers' => $suppliers,
'subtypes' => $subtypes,
'carriers' => $carriers
);
return view('products.index')->with($options);
}
答案 0 :(得分:2)
我可以通过更改控制器功能来修复它。我没有IF声明
$products = Product::with(['supplier', 'carrier', 'name']);
if($request->name) {
$products = $products->whereHas('Name', function ($query) use ($request) {
$query->where('Name', $request->name);
});
}
if($request->subtype) {
$products = $products->whereHas('SubType', function ($query) use ($request) {
$query->where('SubTypeId', $request->subtype);
});
}
if($request->supplier) {
$products = $products->whereHas('Supplier', function ($query) use ($request) {
$query->where('SupplierId', $request->supplier);
});
}
if($request->carrier) {
$products = $products->whereHas('Carrier', function ($query) use ($request) {
$query->where('CarrierId', $request->carrier);
});
}
$products = $products->paginate(8);
$suppliers = Supplier::all();
$carriers = Carrier::all();
$subtypes = SubType::all();
$options = array(
'products' => $products,
'suppliers' => $suppliers,
'subtypes' => $subtypes,
'carriers' => $carriers
);
return view('products.index')->with($options);
在我看来,我放置了分页链接,我替换了
{{ $products->links() }}
与
{{ $products->appends(\Request::except('_token'))->render() }}