2

Currently I'm working on a project search functionality in Laravel and stuck in to get clean GET urls without any kind of JS JS will work too

like when I search my form redirects me to

http://jobs.localhost/search?q=hello

but instead, I want this

http://jobs.localhost/search/hello

My web.php is:

Route::get('search', ['as' => 'search', 'uses' => 'SearchController@search']);

Form is:

<form class="form-inline" method="GET" action="{{ action('SearchController@search') }}" id="search-form">
    <div class="col-md-5 col-sm-5 col-xs-12 nopadding">
        <div class="form-group">

            <input type="text" class="form-control" id="form-q" name="q" placeholder="Search a Job">
            <i class="icon-magnifying-glass"></i>
        </div>
    </div>

    <div class="col-md-2 col-sm-2 col-xs-12 nopadding">
        <div class="form-group form-action">
            <button type="submit" class="btn btn-default btn-search-submit">Search <i class="fa fa-angle-right"></i> </button>
        </div>
    </div>
</form>

Currently In controller I'm just printing the value:

 public function search(Request $request)
 {
  echo $request['q'];  
 }

I've already checked multiple solutions of JS or POST but none works for me this is the final output I'm looking for: http://jobs.localhost/search/hello

Thanks.

Saad Suri
  • 1,352
  • 1
  • 14
  • 26

2 Answers2

2

What you want is route parameters. You can find more info here.

A problem you can (and will) run into is that the route for the form is determined in php (server side), but the search parameter is determined as input. If you don't want any javascript I believe this is impossible without rerouting.

Thijs Steel
  • 1,190
  • 7
  • 16
2

Change route to:

Route::get('search/{search}', ['as' => 'search', 'uses' => 'SearchController@search']);

And controller to:

public function search(Request $request, $search)
{
    echo $search;  
}

Then you'll be able to do something like this with jQuery:

$('#search-form').on('submit', function(e) {
    e.preventDefault();
    var search = $('#form-q').val();
    window.location('/search/' + search);
})
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279