【问题标题】:Accepting a variable number of arguments into a Laravel route?在 Laravel 路由中接受可变数量的参数?
【发布时间】:2014-04-17 01:40:47
【问题描述】:

假设我有以下路线:

Route::post('api/{call}', array('as' => 'apiCaller', 'uses' => 'ApiController@apiCaller'));

我希望这条路由能够调用call 参数中指定的变量API。在call 参数之后,我希望请求者能够以key=value 的典型格式提交帖子,并根据请求的API 使用可变数量的参数。

我该怎么做呢?我应该只检查随请求发送的 $_POST 数组,还是 Laravel 有特殊要求?

【问题讨论】:

  • 你会没事的。您可以使用Input 类访问$_POST$_GET 变量。我真的不认为我可以详细说明,但如果您有具体问题,我可以在详细说明时发布答案。

标签: php laravel laravel-4


【解决方案1】:

您可以使用Input 类从$_POST$_GET 获取任何用户数据,例如:

Input::get('keyname'); // get only one item by keyname
Input::all(); // returns all user submitted data from all input sources
Input::only(array('key1', 'key2')); // Only these two mentioned
Input::except('_token'); // get all but _token

如果你想让用户用url提交数据(不限参数)那么你必须使用query string,例如:

http://example.com?key1=value1&key2=valye2 // So on...

为此,您不必修改您的route,只需在url 中添加参数即可。要提交到$_POST,不需要使用url 传递参数,但是您使用的任何方法(POST/GET),要检索用户提交的数据,您可以使用相同的Input 方法。

【讨论】:

    【解决方案2】:

    正如@Sam 告诉你的那样,只需使用 Input 类:

    class ApiController
    {
    
      public function apiCaller($call)
      {
         $inputs = Input::all();
         // now $inputs is an array with all the key=> value pair sent, or an empty
         // array if none has been passed
      }
    }
    

    这里以及更多内容都写在这里http://laravel.com/docs/requests#basic-input

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-26
      • 2020-06-13
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-11
      相关资源
      最近更新 更多