Reputation: 2972
I would like to generate dynamic route when user clicks on Search
button.
I know it can be done with following GET
method
https://laravel.dev/search?q=parameter
https://laravel.dev/search?state=XYZ&category=Automobile
But instead I would like to do following
https://laravel.dev/search/state/XYZ/category/Automobile
So if I add an extra parameter in search form it will just add onto the URL.
The parameters may be optional so can not add a fix route in routes
. User may supply state or search through all states.
https://laravel.dev/search/category/Automobile
Following is my search form code
<div class="jumbotron">
<!--Search Bar-->
{{ html()->form('GET',route('frontend.search'))->class('form-inline justify-content-center')->open() }}
{{ html()->select('category',$categories)->class('form-control mr-sm-2') }}
{{ html()->select('state',$states)->class('form-control mr-sm-2') }}
<!--More filter to add later-->
<button class="btn btn-outline-primary my-2 my-sm-0" type="submit">Search</button>
{{ html()->form()->close() }}
</div>
How can I achieve that?
Thank you
Upvotes: 2
Views: 475
Reputation: 2951
You can handle the logic with a catch-all route with regular expressions https://laravel.com/docs/7.x/routing#parameters-regular-expression-constraints
//routes.php
Route::get('search/{search?}', 'SearchController@search')
->where('search', '(.*)');
//controller
class SearchController extends BaseController {
public function search($search = null)
{
if ($search != null){
dd($search);
}
}
}
Upvotes: 1
Reputation: 358
Try to use Regex:
Route::get('search/{searchParams}', 'SearchController@search')
->where('searchParams', '[a-zA-Z0-9\/]+');
You can put anything on searchParams
but you need to parse it.
Upvotes: 0