Route::match() not working in nested groups structure

I’m creating an API that is available only via POST. I’m planning to have more than one version of the API, so the current one uses v1 as part of the URL.

Now, in case an API call is made via GET, PUT or DELETE I would like to return a Fail response. For this I’m using Route::match(), which works perfectly fine in the code below:

   Route::group(['namespace'=>'API', 'prefix' => 'api/v1', 'middleware' => 'api.v1'], function() {

        Route::match(['get', 'put', 'delete'], '*', function () {
            return Response::json(array(
                'status' => 'Fail',
                'message' => 'Wrong HTTP verb used for the API call. Please use POST.'
                ));
        });

        // User
        Route::post('user/create', array('uses' => 'APIv1@createUser'));
        Route::post('user/read', array('uses' => 'APIv1@readUser'));
        // other calls

        // University
        Route::post('university/create', array('uses' => 'APIv1@createUniversity'));
        Route::post('university/read', array('uses' => 'APIv1@readUniversity'));
        // other calls...

    });

However, I noticed that I could group the routes even more, to separate the API version and calls to specific entities, like user and university:

Route::group(['namespace'=>'API', 'prefix' => 'api'], function() {

    Route::match(['get', 'put', 'delete'], '*', function () {
        return Response::json(array(
            'status' => 'Fail',
            'message' => 'Wrong HTTP verb used for the API call. Please use POST.'
            ));
    });
    /**
     * v.1
     */
    Route::group(['prefix' => 'v1', 'middleware' => 'api.v1'], function() {

        // User
        Route::group(['prefix' => 'user'], function() {
            Route::post('create', array('uses' => 'APIv1@createUser'));
            Route::post('read', array('uses' => 'APIv1@readUser'));
        });

        // University
        Route::group(['prefix' => 'university'], function() {
            Route::post('create', array('uses' => 'APIv1@createUniversity'));
            Route::post('read/synonym', array('uses' => 'APIv1@readUniversity'));
        });
    });
});

The Route::match() in the code above does not work. When I try to access any API call with e.g. GET, the matching is ignored and I get MethodNotAllowedHttpException.

Can I get the second routes structure to work with Route::match() again? I tried to put it literally everywhere in the groups already. Putting the Route::match() outside of the hole structure and setting path to ‘api/v1/*’ does dot work either.


Source: laravel

Leave a Reply