Laravel:如何发送文本输入作为路由参数?

时间:2018-12-13 15:41:56

标签: php laravel laravel-5 routes query-string

视图

<form method="GET" action="{{ route('searchproduct',['page'=>1]) }}" >
    <input id="q" name="q" type="text" />
    <button type="submit" id="submitButton" class="btn btn-primary">Go</button>
</form>

路线

Route::get('product/search/{page}/{q?}','ProductController@search')->name('searchproduct');

控制器

public function search(Request $request)
    {
        //processing

        return view('products',['products'=> $search_results]);
    }

提交表单后,URL如下所示:

  

example.com/appname/public/product/search/1?q=search+this

我希望它始终像这样:

  

example.com/appname/public/product/search/1/search+this

2 个答案:

答案 0 :(得分:0)

在您的表单中添加ID。

查看

<form id="search" method="GET" action="{{ route('searchproduct',['page'=>1]) }}" >
    <input id="q" name="q" type="text" />
    <button type="submit" id="submitButton" class="btn btn-primary">Go</button>
</form>

JS

jQuery(document).ready(function(){    
    jQuery("form#search").on('submit',function(e){
          e.preventDefault();
          var q = jQuery("#q").val();
          window.location.href = jQuery(this).prop('action')+"/" + encodeURIComponent(q)        
     });
});

答案 1 :(得分:0)

尝试一下

<form id="search" method="POST" action="{{ route('searchproduct',['page'=>1]) }}" >
<input id="q" name="q" type="text" />
<button type="submit" id="submitButton" class="btn btn-primary">Go</button>
</form>

public function search(Request $request,$page,$q='')
{
    //processing

    return view('products',['products'=> $search_results]);
}

Route::post('product/search/{page}/{q?}','ProductController@search')->name('searchproduct');

我猜是由于GET导致您获得example.com/appname/public/product/search/1?q=search+this网址。