I understand that a Resource controller can have the following methods
index
show
create
edit
store
update
destroy
Now suppose I have the following actions which need to be performed in addition to the resource actions:
Are resource controllers useless for the above functionality? If programming an API, I obviously want the index, show, edit,create,destroy... but also the login, find, search etc...
Is it possible to route to both types of controller? e.g.
Route::group(['prefix' => 'api'], function() {
Route::group(['prefix' => 'v1'], function() {
// Resource Controller
Route::resource('posts', 'Api\V1\PostsResourceController');
// Restful Controller
Route::controller('posts', 'Api\V1\PostsController');
});
});
Or should I just forget about the resource controller and use a restful controller instead?
Route::resource: The Route::resource method is a RESTful Controller that generates all the basic routes required for an application and can be easily handled using the controller class.
Router - is what defines how to parse request data. Controller - is what accepts parsed request and generates a response.
A resource controller is used to create a controller that handles all the http requests stored by your application. The resource() is a static function like get() method that gives access to multiple routes that we can use in a controller.
The Default Route Files The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group.
Just use a resource controller, add those other methods to that same controller, and add routes to those methods directly:
Route::group(['prefix' => 'api'], function()
{
Route::group(['prefix' => 'v1', 'namespace' => 'Api\V1'], function()
{
// Add as many routes as you need...
Route::post('login', 'PostsResourceController@login');
Route::get('find', 'PostsResourceController@find');
Route::get('search', 'PostsResourceController@search');
Route::resource('posts', 'PostsResourceController');
});
});
P.S. I generally shy away from using Route::controller()
. It's too ambiguous.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With