1
votes

RESTful and Resource controllers in Laravel 4 are limited that is RESTful method names has to end with get,put,post,patch,delete and Resource controllers has to end with index, create, store,show edit,update,destroy. My question is does Laravel 5 impose the same restrictions?

1
there is no restrictions even at laravel 4. You can add route as many as you want based on what you need. Laravel route::resource only to help you make a cleaner code rather than you need to type each of them and it generate based on general API need.ssuhat

1 Answers

2
votes

Preface

Natively, Yes, it does. Read here. But if you want something different, I give you a trick to do this. First, you may create your own ResourceRegistrar. Mine is [located in app/Routing/ResourceRegistrar.php]:

namespace App\Routing;

use Illuminate\Routing\ResourceRegistrar as BaseRegistrar;

class ResourceRegistrar extends BaseRegistrar
{
}

Then register your own RouteRegistrar in your service provider:

$this->app->bind('Illuminate\Routing\ResourceRegistrar', 'App\Routing\ResourceRegistrar');

Notes: I register my own RouteRegistrar in App\Providers\AppServiceProvider via register method.

Example

I add my own resource controller in routes.php something like this:

Route::resource('photo', 'PhotoController');

So, I should have a PhotoController to handle this request.

Implementation

We know, that a GET request to '/photo' will be handled by PhotoController@index method, to modify your photo:index action to photo:root action, modify your ResourceRegistrar to something like this:

namespace App\Routing;

use Illuminate\Routing\ResourceRegistrar as BaseRegistrar;

class ResourceRegistrar extends BaseRegistrar
{
    protected function addResourceIndex($name, $base, $controller, $options)
    {
        $uri = $this->getResourceUri($name);

        $action = $this->getResourceAction($name, $controller, 'root', $options);

        return $this->router->get($uri, $action);
    }
}

So now GET request to '/photo' will be handled by PhotoController@root method.

Cheat Sheet

Verb      | Path                  | Method to modify  |
----------|-----------------------|-----------------  |
GET       | `/photo`              | addResourceIndex  |
GET       | `/photo/create`       | addResourceCreate |
POST      | `/photo`              | addResourceStore  |
GET       | `/photo/{photo}`      | addResourceShow   |
GET       | `/photo/{photo}/edit` | addResourceEdit   |
PUT/PATCH | `/photo/{photo}`      | addResourceUpdate |
DELETE    | `/photo/{photo}`      | addResourceDestroy|

See the base code of ResourceRegistrar here.