2017-07-29 81 views
3

我想創建一個'Sort By'列表,其中任何列表項都被選中,然後我的laravel php switch語句將返回正確的查詢。我該怎麼做這個?我如何將HTML Select與Switch語句結合起來

到目前爲止,我已經

<select class="form-control" name="SortbyList" > 
    <option value="1">Highest Avg</option> 
    <option value="2">Lowest Avg</option> 
    <option value="3">Another Sort option</option> 
    <option value="2">another sort option</option> 
</select> 

如何使用這跟這將是我的Laravel控制器放置一個開關?

回答

1

既然你沒有表現出任何的代碼,我給你一個簡單的例子:

$data = Model::query(); 

switch (request()->sortByList) { 
    case 1: 
     $data = $data->orderBy('average', 'desc'); 
     break; 
    case 2: 
     $data = $data->orderBy('average', 'asc'); 
     break; 
    ... 
} 

$data = $data->get(); 
-1

你不需要PHP來處理的排序,你可以在客戶端做到這一點,與JS/jQuery。這將完成所有工作而無需刷新頁面。

<script> 
jQuery(document).ready(function() { 

jQuery(".form-control").change(function(){ 
var conceptName = jQuery('#link').find(":selected").text(); 

if(conceptName == "Highest Avg"){ 
    //sorting code here for highest 
} 
if(conceptName == "Lowest Avg"){ 
    // code here 
} 
if(conceptName == "Another Sort option"){ 
    // code here 
} 


}); 
}); 
</script> 
0

我有這一切,但似乎沒有發生在選擇和切換?這裏是所有的代碼,我...

  <select class="form-control" name="SortbyList" > 
       <option value="1">Highest Avg</option> 
       <option value="2">Lowest Avg</option> 
       <option value="3">Another Sort option</option> 
       <option value="2">another sort option</option> 
      </select> 

和控制器:

$productsQuery = Product::where('approved', '=', 1)->leftJoin('reviews', 'reviews.products_id', '=', 'products.id')->select('products.*', DB::raw('AVG(ratings) as ratings_average'))->groupBy('products.id'); 
     switch ($request->SortbyList) { 
      case 1: 
       $productsQuery = $productsQuery->orderBy('ratings_average', 'DESC'); 
       break; 
      case 2: 
       $productsQuery = $productsQuery->orderBy('ratings_average', 'ASC'); 
       break; 
      case 3: 
       $productsQuery = $productsQuery->orderBy('ratings_average', 'ASC'); 
       break; 
      case 4: 
       $productsQuery = $productsQuery->orderBy('ratings_average', 'ASC'); 
       break; 
       default: 
        $productsQuery = $productsQuery->orderBy('ratings_average', 'DESC'); 


     } 



     $name=$request->input('productname'); 
     $count=$request->input('country_id'); 


     if(!empty($name)){ 
      $productsQuery->where('productname', 'LIKE', '%'.$name.'%')->get(); 
     } 
     if(!empty($count)){ 
      $ProductsQuery->where('country_id', $request->input('country_id'))->get(); 
     } 
     $products= $ProductsQuery->paginate(10); 

藉口的情況下3和4 IM尚未進行編碼。