【问题标题】:Access query string values from Laravel从 Laravel 访问查询字符串值
【发布时间】:2014-09-04 20:36:55
【问题描述】:

有谁知道是否可以在 Laravel 中使用 URL 查询。

示例

我有以下路线:

Route::get('/text', 'TextController@index');

该页面上的文本基于以下 url 查询:

http://example.com/text?color={COLOR}

我将如何在 Laravel 中解决这个问题?

【问题讨论】:

    标签: php laravel laravel-4 query-string laravel-routing


    【解决方案1】:
    public function fetchQuery(Request $request){
      $object = $request->query('object');
      $value = $request->query('value');
    }
    

    【讨论】:

      【解决方案2】:

      对于未来的访问者,我对> 5.0 使用以下方法。它利用了 Laravel 的 Request class 并且可以帮助将业务逻辑排除在您的 routescontroller 之外。

      示例网址

      admin.website.com/get-grid-value?object=Foo&value=Bar
      

      Routes.php

      Route::get('get-grid-value', 'YourController@getGridValue');
      

      YourController.php

      /**
       * $request is an array of data
       */
      public function getGridValue(Request $request)
      {
          // returns "Foo"
          $object = $request->query('object');
      
          // returns "Bar"
          $value = $request->query('value');
      
          // returns array of entire input query...can now use $query['value'], etc. to access data
          $query = $request->all();
      
          // Or to keep business logic out of controller, I use like:
          $n = new MyClass($request->all());
          $n->doSomething();
          $n->etc();
      }
      

      有关从请求对象检索输入的更多信息,read the docs

      【讨论】:

      • 这是 $request->query('object');查询字符串参数。
      【解决方案3】:

      查询参数是这样使用的:

      use Illuminate\Http\Request;
      
      class ColorController extends BaseController{
      
          public function index(Request $request){
               $color = $request->query('color');
          }
      

      【讨论】:

        【解决方案4】:

        是的,这是可能的。试试这个:

        Route::get('test', function(){
            return "<h1>" . Input::get("color") . "</h1>";
        });
        

        并通过转到http://example.com/test?color=red 来调用它。

        当然,您可以通过附加参数来扩展它,以满足您的需求。试试这个:

        Route::get('test', function(){
            return "<pre>" . print_r(Input::all(), true) . "</pre>";
        });
        

        并添加更多参数:

        http://example.com/?color=red&time=now&greeting=bonjour`
        

        这会给你

        Array
        (
            [color] => red
            [time] => now
            [greeting] => bonjour
        )
        

        【讨论】:

        • 为什么在这个例子中使用 Input 对象而不是 Request 对象?
        • @MattCatellier 我相信请求对象适用于 Laravel 版本 >= 5.0
        • 别忘了在进口附近添加use Illuminate\Http\Request;
        猜你喜欢
        • 2013-07-06
        • 2012-02-16
        • 1970-01-01
        • 2021-09-14
        • 1970-01-01
        • 1970-01-01
        • 2018-03-05
        • 2014-02-15
        • 1970-01-01
        相关资源
        最近更新 更多