phplaravellaravel-bladeclean-url

How to get clean GET urls for search in laravel 5.4


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.


Solution

  • 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);
    })