php - How to get clean GET urls for search in laravel 5.4

373

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' => '[email protected]']);

Form is:

<form class="form-inline" method="GET" action="{{ action('[email protected]') }}" id="search-form">
  <div >
    <div >

      <input type="text" id="form-q" name="q" placeholder="Search a Job">
      <i ></i>
    </div>
  </div>

  <div >
    <div >
      <button type="submit" >Search <i ></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.

751

Answer

Solution:

Change route to:

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

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

Answer

Solution:

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.

People are also looking for solutions to the problem: character encoding - Mail sent using PHP form showing garbled Japanese text

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.