2017-10-09 127 views
1

我創建了一些使用文本框和下拉菜單的搜索過濾器,所以當我單擊搜索按鈕時,我想使用這些過濾器中的任何一個來查詢雄辯的關係。Laravel 5搜索結果分頁

搜索工作正常,我得到正確數量的結果,但問題在於分頁。當我點擊下一頁按鈕(或任何其他頁面)時,結果就是結果,我再次得到一切。

我知道這一點,因爲我沒有做單擊分頁時的請求,所以我的問題是我如何執行如此相同的查詢,但使用分頁?

這裏是我的控制器功能

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

不相關的問題,但只是一個側面說明:您不需要執行'$ products = $ query-> where(...)',只需要'$ query-> where(...)'就足夠了。 – madpoet

回答

1

我能夠通過改變控制器功能來修復它。我沒有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() }}