I want to create a 'Sort By' List in which whatever list item is selected then my laravel php switch statement will come back with the correct query.. How do i do this?
So far i have
<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>
How do i use this with a switch which will be place in my Laravel Controller?
Since you didn't show any code, I'll give you a simple example:
$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();
You don't need to process the Sorting with PHP, you can do this on the client side, with JS/jQuery. This will do all work without refreshing the page.
<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>
I have all this but nothing seems to happen in terms of the select and switch? here is all the code i have...
<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>
And controller:
$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);
Excuse case 3 and 4 im yet to code them.