Form action to URL, best way.
Hey,
I have a website where I showcase products that is filtered by category and sorted by price. I am trying to find the most effective way of coding it. What I have in mind is something like the searchAction(). This is what I currently have.
Example url, I want the category, color and sort to be shown in the url
/search/pants/red/price
My route has two optional parameter:
Route::get('/search/{category}/{color?}/{sort?}', 'ProductController@search')->name('search')
My controller:
search($category, $color = 0, $sort = 0){
// $products = load products.json : contains all products(100 total)
// loop trough all products
foreach($products as $product => $item){
// is color set as filter?
if($color !== 0) {
$item->show = false; // don't show the item in the list
// Is this item same color as filter?
if (stripos($item->color, $color) !== false) {
$item->show = true; // Show the item, same color
}
}else{
// color filter is not set.
$item->show = true;
}
// Do the same for category as I did for color.
}
// Do sorting
This is what I currently have simplified. It works if I manually type the URL, but I want to do it via a form and that's where I want to be effective as possible.
Create a new method and redirect it to the search method with the parameters set:
searchAction(Request $request){
// validate input, if the value is not set then set it to 0
// if: sort or color is set
return redirect()->route('search', ['category' => $request->category, 'color' => $request->color, 'sort' => $request->sort]);
// else just show the category
return redirect()->route('search', ['category' => $request->category]);
}
Something tells me there is a better way of doing it. Maybe remove searchAction() entirely and let search() handle the requests? Or maybe there is a way getting the value of an input in blade view.
Form::open(['route' => ['search', 'categoryInput']])
From
Form::text('categoryInput')
That would be the cleanest and easiest solution IMO. Let me know what you think, and if you know how to get it inside the blade view or if you have a better solution.
Thanks.
Please or to participate in this conversation.