如何将查询字符串参数传递给 Laravel4 中的路由 [英] How to pass query string params to routes in Laravel4

查看:31
本文介绍了如何将查询字符串参数传递给 Laravel4 中的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Laravel 4 中编写一个 api.我想将查询字符串参数传递给我的控制器.具体来说,我想允许这样的事情:

I'm writing an api in Laravel 4. I'd like to pass query string parameters to my controllers. Specifically, I want to allow something like this:

api/v1/account?fields=email,acct_type

查询参数被传递给路由控制器方法,该方法具有如下签名:

where the query params are passed along to the routed controller method which has a signature like this:

public function index($cols)

routes.php 中的路由如下所示:

The route in routes.php looks like this:

Route::get('account', 'AccountApiController@index');

为了清晰和灵活,我手动指定所有路由(而不是使用 Route::controllerRoute::resource)并且我总是路由到控制器和方法.

I am manually specifying all my routes for clarity and flexibility (rather than using Route::controller or Route::resource) and I am always routing to a controller and method.

我创建了一个(全局)辅助函数,它将字段"查询字符串元素隔离到一个数组 $cols 中,但是在每个控制器的每个方法中调用该函数并不是 DRY.如何有效地将 $cols 变量传递给我所有的 Route::get 路由的控制器方法?或者,更一般地说,如何通过路由(或一组路由)将查询字符串中的一个或多个额外参数有效地传递到控制器方法?我正在考虑使用过滤器,但这似乎有点不合规格.

I made a (global) helper function that isolates the 'fields' query string element into an array $cols, but calling that function inside every method of every controller isn't DRY. How can I effectively pass the $cols variable to all of my Route::get routes' controller methods? Or, more generally, how can I efficiently pass one or more extra parameters from a query string through a route (or group of routes) to a controller method? I'm thinking about using a filter, but that seems a bit off-label.

推荐答案

您可能希望在 BaseController 中实现它.这是可能的解决方案之一:

You might want to implement this in your BaseController. This is one of the possible solutions:

class BaseController extends Controller {

    protected $fields;

    public function __construct(){

        if (Input::has('fields')) {
            $this->fields = Input::get('fields');
        }
    }
}

之后可以在每个 BaseController 子路由中访问 $fields:

After that $fields could be accessed in every route which is BaseController child:

class AccountApiController extends \BaseController {

    public function index()
    {
        dd($this->fields);
    }
} 

这篇关于如何将查询字符串参数传递给 Laravel4 中的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆