cosmoloc
cosmoloc

Reputation: 2994

Laravel routing to wrong controller method

I have following 2 routes :

Route1:

Route::get(config('api.basepath') . '{username}/{hash}/{object_id}', [
    'action' => 'getObject',
    'uses' => 'ObjectController@getObject',
]);

and

Route2:

Route::get(config('api.basepath') . 'object-boxes/{object_id}/boxes', function () {
    if (Input::get('action') == 'filter') {
        return App::call('App\Http\Controllers\FilterController@getFilteredContents');
    } else {
        return App::call('App\Http\Controllers\ObjectBoxController@show');
    }
});

Now,

Route 1 is available with or without Auth middleware, while Route2 is under Auth middleware.

But, In either call, execution control is going to ObjectController@getObject

When I move Route1 below Route2, then everytime the call goes to ObjectBoxController@show.

I tried Preceed but nothing changed. How should I fix this

Upvotes: 2

Views: 1247

Answers (2)

Sagar Gautam
Sagar Gautam

Reputation: 9359

Your first and second route are similar,

First Route

config('api.basepath') . '{username}/{hash}/{object_id}'

Second Route

config('api.basepath') . 'object-boxes/{object_id}/boxes'

when you have second route case, it has been treated as former one and takes username as object-boxes and object_id as boxes. So same function is called for both cases. So, try with something different route pattern for these two routes.

Upvotes: 4

Douwe de Haan
Douwe de Haan

Reputation: 6646

You should define what the variables in the routes are going to be, not the where at the end of each route:

Route::get(config('api.basepath') . '{username}/{hash}/{object_id}', [
    'action' => 'getObject',
    'uses' => 'ObjectController@getObject',
])->where('object_id', '[0-9]+');

Route::get(config('api.basepath') . 'object-boxes/{object_id}/boxes', function () {
    if (Input::get('action') == 'filter') {
        return App::call('App\Http\Controllers\FilterController@getFilteredContents');
    } else {
        return App::call('App\Http\Controllers\ObjectBoxController@show');
    }
})->where('object_id', '[0-9]+');

You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained:

Read the documentation here

Upvotes: 2

Related Questions