Eamorr
Eamorr

Reputation: 10012

Laravel routing woes

I have this routing which is working great:

Route::get('/', 'MainController@index');
Route::get('about', 'MainController@about');
Route::get('contact', 'MainController@contact');
Route::get('signUp', 'MainController@signUp');

The correct functions in MainController.php get called as expected.

Where I'm having trouble is in getting the following to work:

I have a new file called APIController.php. All requests to http://eamorr.com/api/getUsers should be handled by getUsers() in APIController.php.

I tried this:

Route::get('api', 'APIController@index');   //this works fine...
Route::any('api/{$function}', function($function){   //but this won't work!
    return redirect()->route('api/'.$function);
});

I don't want to list every function like:

Route::get('api/addUser', 'APIController@addUser');
Route::get('api/getUser', 'APIController@getUser');
Route::get('api/getAllUsers', 'APIController@getAllUsers');
...

I'd prefer if /api/* requests just get directed to APIController...

If anyone has any tips, that would be really great...

I only started learning Laravel yesterday, so please go easy on me!

Upvotes: 3

Views: 72

Answers (2)

Sh1d0w
Sh1d0w

Reputation: 9520

You have the Route::controller method which will bind your class as implict controller:

Route::controller('api', 'APIContoller');

This will declare new Implict Controller which will map automatically all of your calls to the controller methods prefixed with the request type.

So if you do GET request to /api/users, this will trigger getUsers method of APIController. If you do POST request to /api/users it will trigger postUsers method, etc.

You can read more about Implict Controllers in the documentation.

Upvotes: 0

Bogdan
Bogdan

Reputation: 44526

You could call the controller action like this:

Route::any('/api/{action}', function($action)
{
    // this will call the method from the controller class and return it's response
    return app()->make('App\Http\Controllers\ApiController')->callAction($action, []);
});

However I suggest you look into Implicit Controllers as @shaddy suggested in his answer, because actions such as addUser would require restricting the HTTP verb to POST, which you can't do properly with this approach.


Also, since from your route path it looks like you're building an API, you might want to look into using RESTful Resource Controllers.

Upvotes: 1

Related Questions