Besnik Cani
Besnik Cani

Reputation: 29

Laravel routes not working inside a prefix unless given a variable

I'm fairly new to Laravel. I'm having a problem with routing.

Route::group(['prefix'=>'api/v1'],function(){
  Route::resource('results','RequestController');
  Route::get('results/getByName/{name}','RequestController@getByName');
  Route::get('results/getLastTen','RequestController@getLastTen');
});

The problem is that the last route under prefix api/v1 does not work. When I call it it shows nothing, not even any error.

The code at the requestController is:

public function getLastTen(){
        $results=DB::table('latest_random_trends')->limit(10)->get();
        return $results;
    }

Everything is alright with the code on the controller since it works when I call it from the routes.php file outside of the prefix 'api/v1' like this:

    Route::get('results/getLastTen','RequestController@getLastTen');

but when it is inside the prefix it does not work unless I add a variable to it like this:

    Route::get('results/getLastTen/{var}','RequestController@getLastTen');

Upvotes: 0

Views: 3298

Answers (1)

Lloople
Lloople

Reputation: 1844

Since you have a Route::resource above it, I think what's happening is that the show method on Resource Controller is getting the route instead of the one you wrote.

Try one the following:

  • Exclude the show method if you're not going to use it

    Route::resource('results','RequestController', ['except' => 'show']);
    
  • Move your custom route above the resource route

    Route::group(['prefix'=>'api/v1'],function(){
        Route::get('results/getLastTen','RequestController@getLastTen');
        Route::resource('results','RequestController');       
        Route::get('results/getByName/{name}', 'RequestController@getByName');
    
    });
    

For more information, check out the show action on Laravel Docs

Upvotes: 2

Related Questions