2017-08-07 58 views
-3

我想知道如何在我的應用程序中使價格過濾器?價格過濾laravel基地

我使用laravel 5.4

我現在有這樣的事情:

public function indexproduct(Request $request) { 
     $query = Product::orderBy('created_at','desc'); 
     if($request->keyword){ 
      // This will only executed if you received any keyword 
      $query = $query->where('title','like','%'.$keyword.'%'); 
     } 
     if($request->min_price && $request->max_price){ 
      // This will only executed if you received any price 
      // Make you you validated the min and max price properly 
      $query = $query->where('price','>=',$request->min_price); 
      $query = $query->where('price','<=',$request->max_price); 
     } 
     $products = $query->paginate(6); 
     return view('frontend.shop', compact('products')); 
    } 

查看:

<form class="form-inline" action="{{route('shop')}}" method="GET"> 
      Min <input class="form-control" type="text" name="min_price"> 
      Max <input class="form-control" type="text" name="max_price"> 
      Keyword <input class="form-control" type="text" name="keyword" > 
      <input class="btn btn-default" type="submit" value="Filter"> 
     </form> 

,它會顯示我的產品。我還希望在我的產品頂部添加過濾器選擇框,以便用戶過濾結果。

更新:現在將加載頁面,但沒有結果,它只是刷新 頁!

database

+0

你試過了什麼?你傳遞了什麼變量? –

+0

目前無!因爲我不知道該怎麼做! –

+0

檢查我的答案。我希望你能提供更多的信息,如模型,表名,與問題相關的視圖。 –

回答

1

首先,你應該創建一個表單,你可以把你所有的過濾器。

<form action="{{ url('url/to/your/indexproduct')}}" method="GET"> 
    <input type="text" name="min_price"> //User can input minimum price here 
    <input type="text" name="max_price"> //User can input maximun price here 
    <input type="text" name="keyword" > // User can input name or description 
    <input type="submit" value="Filter"> 
</form> 

之後,您的控制器將在點擊提交按鈕後從該表單接收數據。所以如果你想檢查它。像這樣做。

public function indexproduct(Illuminate\Http\Request $request) { 
    dd($request->all()) // This will show all your filters 
} 

然後當你是你的數據發送到你的控制器,你應該修改你的查詢,幷包括你的過濾器。 (有很多方法可以做,但這是一個簡單的方法)

public function indexproduct(Illuminate\Http\Request $request) { 
    $query = Product::orderBy('created_at','desc'); 
    if($request->keyword){ 
     // This will only execute if you received any keyword 
     $query = $query->where('name','like','%'.$keyword.'%'); 
    } 
    if($request->min_price && $request->max_price){ 
     // This will only execute if you received any price 
     // Make you you validated the min and max price properly 
     $query = $query->where('price','>=',$request->min_price); 
     $query = $query->where('price','<=',$request->max_price); 
    } 
    $products = $query->paginate(5); 
    return view('frontend.shop', compact('products')); 
} 

我希望它能幫助你。

+0

好吧bro現在我得到這個錯誤'方法鏈接不存在.'持有我也會更新我的問題。 –

+0

我修改了我的答案,我忘了你的分頁。 '$ products = $ query-> paginate(5);'。你的錯誤可能是分頁。 –

+0

現在會加載頁面,但沒有結果,它只是刷新頁面! –