Patryk Przybylski
Patryk Przybylski

Reputation: 53

Laravel sortby after select specific option

I would like to add a select field in my application with the option of choosing to sort products by date of addition or price. After selecting a specific option, e.g. sort by price, products returned from the cheapest are returned. I know how to sort products but I do not know how to do it to show sorted products after selecting a specific option, e.g. sort by price. My code :

web.php

Route::get('/{category}', 'ProductController@index');

ProductController:

public function index()
    {          
        $products= Product::latest()->get();
        return view('category')->with('products', $products);
    }

Upvotes: 0

Views: 1472

Answers (1)

Piazzi
Piazzi

Reputation: 2636

In your view you could use a form like this to get wich category the user wants to filter:

<form method="get" action="{{route('product.index')}}">
@csrf
 <select name="category">
  <option value="price">Price</option>
  <option value="date">Date</option>
 </select>
 <button type="submit">Search</button>
</form>

And in your controller you can filter the collection using the selected option:

public function index(Request $request)
    {          
        $products= Product::all()->sortBy($request->category);
        return view('category')->with('products', $products);
    }

Upvotes: 1

Related Questions