简体   繁体   中英

RESTful and Resource Controllers in Laravel 4 and 5

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM