How to pass query string params to routes in Larav

2019-02-15 11:31发布

问题:

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