Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

php - 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', 'ApiV1PostsResourceController');

        // Restful Controller
        Route::controller('posts', 'ApiV1PostsController');
    });
});

Or should I just forget about the resource controller and use a restful controller instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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' => 'ApiV1'], 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...