Laravel wastes troubles

I have this routing that works 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

are called as expected.

In cases where I have problems, you get the following:

I have a new file named APIController.php

. All requests to http://eamorr.com/ api / getUsers should be processed getUsers()

in APIController.php

.

I've 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 would prefer that requests are /api/*

simply redirected to APIController ...

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

I just started learning Laravel yesterday, so please take it easy!

+3


source to share


2 answers


You can call a controller action like this:

Route::any('/api/{action}', function($action)
{
    // this will call the method from the controller class and return it 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 like addUser

, require an HTTP verb constraint POST

, which you can't do right with this approach.




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

+1


source


You have a method Route::controller

that will bind your class to the implict controller:

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

      

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



So, if you make a GET request for /api/users

, this will call the getUsers

APIController method . If you make a POST request to /api/users

, it calls a method postUsers

, etc.

You can read more about Implict Controllers in the documentation .

0


source







All Articles