Laravel 4.2 Form SUbmit Friendly URL

1.3k views Asked by At

I have a form in Laravel 4.2

{{Form::open(array('url'=>'search', 'method'=>'get', 'class'=>'navbar-form navbar-left' ,'role'=>'search'))}}
<div class="form-group ">
   <input list="browsers" name="topic" class="form-control " placeholder="Search">
     <datalist id="browsers">
        <option value="Internet Explorer">
        <option value="Firefox">
        <option value="Chrome">
        <option value="Opera">
        <option value="Safari">
     </datalist>
</div>
<button class="gray-button"><span>Search</span></button>
{{Form::close()}}

When I Click on submit button, I get URL like

http://localhost/car/public/search?topic=dfg

But I want to have a URL like

http://localhost/car/public/search/dfg

Do I need to change some code in Form?

Or in Router.

Can anyone help me please?

Thanks in advance for helping.

1

There are 1 answers

0
Bogdan On BEST ANSWER

You do need JavaScript if you don't want to do a server redirect as @lukasgeiter pointed in the comments. You also need to setup a route for that particular search URL. The route should look something like this using a route closure:

Route::get('search/{topic}', function ($topic)
{
    // code goes here
});

For the client side you need to stop the form from submitting and go to a manually built URL when submitting the form. So you could have something like this:

{{Form::open(array('url'=>'search', 'method'=>'get', 'id' => 'searchForm', 'class'=>'navbar-form navbar-left' ,'role'=>'search'))}}
    <div class="form-group ">
       <input list="browsers" name="topic" class="form-control " placeholder="Search">
         <datalist id="browsers">
            <option value="Internet Explorer">
            <option value="Firefox">
            <option value="Chrome">
            <option value="Opera">
            <option value="Safari">
         </datalist>
    </div>
    <button class="gray-button"><span>Search</span></button>
{{Form::close()}}

<script>
    document.getElementById('searchForm').onsubmit = function (event)
    {
        // Prevent the form from submitting
        event.preventDefault();

        // Build the url using the form action and the topic value
        var topic = document.querySelectorAll('input[name="topic"]')[0];
        window.location.href = this.action + '/' + encodeURIComponent(topic.value);
    };
</script>