简体   繁体   中英

Laravel passing parameters to controller from route

I am creating an API for my Laravel project. I have included my API authentication directly in my route.php file. After validation passes, I want to be able to pass my $api parameter to the controller itself to use. As you will see below I appended ->with() after my Route:post call but that is failing. How can I pass $api to my control?

Thanks in advance!

Route::group(array('prefix' => 'api/1.0.0'), function()
{
    $api = Api::checkCredentials(Input::get('username'), Input::get('api_key'));

    if($api)
    {
        Route::post('beacons/fetch', 'ApiController@fetchBeacons')->with('api', $api);
    }
    else
    {
        return Response::json(array(
            'error' => true,
            'output' => 'Invalid API credentials'),
            200
        );
    }
});

You may use before filter, for example:

Route::group(array('prefix' => 'api/1.0.0'), function()
{
    Route::post(
        'beacons/fetch',
        array('before' => 'checkUser', 'uses' => 'ApiController@fetchBeacons')
    );
});

Declare the checkUser filter which will be executed before the route is dispatched:

Route::filter('checkUser', function($route, $request) {

    $inputs = Input::only(array('username', 'api_key'));

    $api = app('Api')->checkCredentials($inputs);

    if(!$api) {

        return Response::json(array(
            'error' => true,
            'output' => 'Invalid API credentials'),
            200
        );
    }
    else {
        Input::merge(array('api' => $api));
    }
});

So now, you may access the api in your controller using this:

$api = Input::get('api');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM