How to pass query string params to routes in Laravel4

烂漫一生 提交于 2019-12-19 04:16:06

问题


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)

The route in routes.php looks like this:

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

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.

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.


回答1:


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');
        }
    }
}

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

class AccountApiController extends \BaseController {

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


来源:https://stackoverflow.com/questions/20321274/how-to-pass-query-string-params-to-routes-in-laravel4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!