php 如何使用 GET 方法将 GET 参数传递给 Laravel?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27298426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:17:46  来源:igfitidea点击:

How To Pass GET Parameters To Laravel From With GET Method ?

phpformslaravel

提问by Iliyass Hamza

i'm stuck at this very basic form, that i could not accomplish, which i want to build a search form with an text input, and two select controls, with a route that accept 3 parameters, the problem that when the i submit the form, it map the parameters with the question mark, not the Laravel way,

我被困在这个非常基本的表单上,我无法完成,我想构建一个带有文本输入和两个选择控件的搜索表单,以及一个接受 3 个参数的路由,问题是当我提交形式,它用问号映射参数,而不是Laravel的方式,

Markup

标记

{{ Form::open(['route' => 'search', 'method' => 'GET'])}}
    <input type="text" name="term"/>
    <select name="category" id="">
        <option value="auto">Auto</option>
        <option value="moto">Moto</option>
    </select>
    {{ Form::submit('Send') }}
{{ Form::close() }}

Route

路线

    Route::get('/search/{category}/{term}', ['as' => 'search', 'uses' => 'SearchController@search']);

When i submit the form it redirect me to

当我提交表单时,它会将我重定向到

search/%7Bcategory%7D/%7Bterm%7D?term=asdasd&category=auto

How can i pass these paramters to my route with the Laravel way, and without Javascript ! :D

我如何使用 Laravel 方式将这些参数传递到我的路线,而没有 Javascript!:D

回答by msturdy

The simplest way is just to accept the incoming request, and pull out the variables you want in the Controller:

最简单的方法就是接受传入的请求,在Controller中拉出你想要的变量:

Route::get('search', ['as' => 'search', 'uses' => 'SearchController@search']);

and then in SearchController@search:

然后在SearchController@search

class SearchController extends BaseController {

    public function search()
    {
        $category = Input::get('category', 'default category');
        $term = Input::get('term', false);

        // do things with them...
    }
}

Usefully, you can set defaults in Input::get()in case nothing is passed to your Controller's action.

有用的是,您可以设置默认值,Input::get()以防没有任何内容传递给您的 Controller 的操作。

As joe_archer says, it's not necessary to put these terms into the URL, and it might be better as a POST (in which case you should update your call to Form::open()and also your search route in routes.php - Input::get()remains the same)

正如 joe_archer 所说,没有必要将这些术语放入 URL,并且作为 POST 可能更好(在这种情况下,您应该更新您的呼叫Form::open()以及您在 routes.php 中的搜索路线 -Input::get()保持不变)

回答by birchy

I was struggling with this too and finally got it to work.

我也为此苦苦挣扎,终于让它发挥作用。

routes.php

路由文件

Route::get('people', 'PeopleController@index');
Route::get('people/{lastName}', 'PeopleController@show');
Route::get('people/{lastName}/{firstName}', 'PeopleController@show');
Route::post('people', 'PeopleController@processForm');

PeopleController.php

人员控制器.php

namespace App\Http\Controllers ;
use DB ;
use Illuminate\Http\Request ;
use App\Http\Requests ;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;

    public function processForm() {
        $lastName  = Input::get('lastName') ;
        $firstName = Input::get('firstName') ;
        return Redirect::to('people/'.$lastName.'/'.$firstName) ;
    }
    public function show($lastName,$firstName) {
        $qry = 'SELECT * FROM tableFoo WHERE LastName LIKE "'.$lastName.'" AND GivenNames LIKE "'.$firstName.'%" ' ;
        $ppl = DB::select($qry);
        return view('people.show', ['ppl' => $ppl] ) ;
    }

people/show.blade.php

人/show.blade.php

<form method="post" action="/people">
    <input type="text" name="firstName" placeholder="First name">
    <input type="text" name="lastName" placeholder="Last name">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="submit" value="Search">
</form>

Notes:
I needed to pass two input fields into the URI.
I'm not using Eloquent yet, if you are, adjust the database logic accordingly.
And I'm not done securing the user entered data, so chill.
Pay attention to the "_token" hidden form field and all the "use" includes, they are needed.

注意:
我需要将两个输入字段传递到 URI 中。
我还没有使用 Eloquent,如果你正在使用,请相应地调整数据库逻辑。
我还没有完成保护用户输入的数据,所以冷静。
注意“_token”隐藏表单字段和所有“使用”包含,它们是必需的。

PS: Here's another syntax that seems to work, and does not need the

PS:这是另一种似乎有效的语法,不需要

use Illuminate\Support\Facades\Input;

.

.

public function processForm(Request $request) {
    $lastName  = addslashes($request->lastName) ;
    $firstName = addslashes($request->firstName) ;
    //add more logic to validate and secure user entered data before turning it loose in a query
    return Redirect::to('people/'.$lastName.'/'.$firstName) ;
}

回答by Fabian M

I had same problem. I need show url for a search engine

我有同样的问题。我需要显示搜索引擎的网址

I use two routes like this

我使用两条这样的路线

Route::get('buscar/{nom}', 'FrontController@buscarPrd');

Route::post('buscar', function(){

   $bsqd = Input::get('nom');    

   return Redirect::action('FrontController@buscarPrd', array('nom'=>$bsqd));

});

First one used to show url like we want

第一个用于显示我们想要的网址

Second one used by form and redirect to first one

表单使用的第二个并重定向到第一个

回答by Jonathan

An alternative to msturdy's solutionis using the request helper methodavailable to you.

msturdy 解决方案的替代方法是使用您可用的请求助手方法

This works in exactly the same way, without the need to import the Inputnamespace use Illuminate\Support\Facades\Inputat the top of your controller.

这以完全相同的方式工作,无需在控制器顶部导入Input命名空间use Illuminate\Support\Facades\Input

For example:

例如:

class SearchController extends BaseController {

    public function search()
    {
        $category = request('category', 'default');
        $term = request('term'); // no default defined

        ...
    }
}

回答by Joe

So you're trying to get the search term and category into the URL?

因此,您正在尝试将搜索词和类别放入 URL 中?

I would advise against this as you'll have to deal with multi-word search terms etc, and could end up with all manner of unpleasantness with disallowed characters.

我建议不要这样做,因为您将不得不处理多词搜索词等,并且最终可能会因不允许使用的字符而导致各种不愉快。

I would suggest POSTing the data, sanitising it and then returning a results page.

我建议发布数据,对其进行消毒,然后返回结果页面。

Laravel routing is not designed to accept GET requests from forms, it is designed to use URL segments as get parameters, and built around that idea.

Laravel 路由并不是为了接受来自表单的 GET 请求,它被设计为使用 URL 段作为获取参数,并围绕这个想法构建。

回答by Ayoub Bousetta

Router

路由器

Route::get('search/{id}', ['as' => 'search', 'uses' => 'SearchController@search']);

Controller

控制器

class SearchController extends BaseController {

    public function search(Request $request){

        $id= $request->id ; // or any params

        ...
    }
}

回答by b.b3rn4rd

Alternatively, if you want to specify expected parameters in action signature, but pass them as arbitrary GETarguments. Use filters, for example:

或者,如果您想在动作签名中指定预期参数,但将它们作为任意GET参数传递。使用过滤器,例如:

Create a route without parameters:

创建不带参数的路由:

$Route::get('/history', ['uses'=>'ExampleController@history']);

Specify action with two parameters and attach the filter:

使用两个参数指定操作并附加过滤器:

class ExampleController extends BaseController
{
    public function __construct($browser)
    {
        $this->beforeFilter('filterDates', array(
            'only' => array('history')
        ));
    }

    public function history($fromDate, $toDate)
    {
        /* ... */
    }

}

Filter that translates GETinto action's arguments :

转换GET为动作参数的过滤器:

Route::filter('filterDates', function($route, Request $request) {
    $notSpecified = '_';

    $fromDate = $request->get('fromDate', $notSpecified);
    $toDate = $request->get('toDate', $notSpecified);

    $route->setParameter('fromDate', $fromDate);
    $route->setParameter('toDate', $toDate);
});