Question

I'm working on a website that searches a database of organizations. On the search page, there are two search fields: one for searching by record name, and one searching the organization's subjects.

Now, normally, I would have no problem setting up placeholders in my URIs.

Route::get('/search/{name}', function($name)
{
    //code...
});

And I use the post route to attach the parameters

Route::post('/search', array( 'as' => 'results', function()
{
    $string = Input::get('search');
    return Redirect::to("/search/$string");
}));

And the Laravel form would have no problem...

<h4>Search by Name</h4>
{{ Form::open(array('url' => "search") )}}
<p>
    <div class="input-group input-group-lg">
    <span class="input-group-btn">
        {{ Form::button('Search', array('class' => 'btn btn-default', 'type' => 'submit'))}}
    </span>
    {{ Form::text('search', '', array('class' => 'form-control', 'placeholder' => 'Search by name')) }}
</div>

</p>
{{ Form::close() }}

But how do I attach a query string to this part?

{{ Form::open(array('url' => "search") )}}

How I would like my code to behave is when a query string is present, it searches by subject, not name. Doing this:

{{ Form::open(array('url' => "search/?subject=true") )}}

Doesn't actually attach it to my url.

The one thing I could do is just have a hidden input that tells the code to search by subject and not name, but that would mean any users who go to the url again will get different results. I don't want that behavior.

Any help? Laravel documentation doesn't help and I can't seem to find anyone online with the same problem.

[edit] I found the trick to putting it into the url is by attaching the query string on the Route::post() like so:

$string = Input::get('search');
$subject = Input::get('subject');
return Redirect::to("/search/$string?subject=$subject");

But then Laravel gives me a NotFoundHttpException even after I change the final route to

Route::get('/search/{name}?subject={subject}', function($name, $subject)
Was it helpful?

Solution

Try

Route::get('/search',function($name)
{
    //code...
    if(Input::has('subject'))
        $subject = Input::get('subject');
    ...
});

OTHER TIPS

Laravel Router system already adds all of your non-route parameters as queries, so if you have a router:

Route::get('/search/{name?}', ['as' => 'search', function($name)
{
    //code...
}]);

And you do

return Redirect::route('search', ['name' => 'laracon', 'subject' => 'true']);

It will redirect to:

http://server/search/laracon?subject=true

And

return Redirect::route('search', ['subject' => 'true']);

To

http://server/search?subject=true

And, of course, inside your router you have access to both of them:

Route::get('/search/{name?}', ['as' => 'search', function($name)
{
    var_dump(Input::get('name'));

    var_dump(Input::get('search'));
}]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top