Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 - Route::resource vs Route::controller. Which to use?

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:

  • User attempts to log in.
  • Admin wishes to find a user by email / first-name
  • User requests a post by it's slug

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?

like image 738
Gravy Avatar asked Sep 30 '13 19:09

Gravy


People also ask

What is route :: resource?

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.

What is the notable difference of the controller and router in Laravel?

Router - is what defines how to parse request data. Controller - is what accepts parsed request and generates a response.

What is resource controller in Laravel?

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.

What are the default route files in Laravel?

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.


1 Answers

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.

like image 109
Joseph Silber Avatar answered Sep 20 '22 07:09

Joseph Silber