Laravel 4中的RESTful和资源控制器是有限的,即RESTful方法名称必须以get,put,post,patch,delete结尾,资源控制器必须以index,create,store,show edit,update,destroy结尾。我的问题是 Laravel 5 是否施加了相同的限制?
前言
从本质上讲,是的,确实如此。在这里阅读。但是如果你想要一些不同的东西,我给你一个技巧来做到这一点。首先,您可以创建自己的ResourceRegistrar
。我的是 [位于app/Routing/ResourceRegistrar.php
]:
namespace App'Routing;
use Illuminate'Routing'ResourceRegistrar as BaseRegistrar;
class ResourceRegistrar extends BaseRegistrar
{
}
然后在服务提供商处注册您自己的RouteRegistrar
:
$this->app->bind('Illuminate'Routing'ResourceRegistrar', 'App'Routing'ResourceRegistrar');
注意:我通过
register
方法在App'Providers'AppServiceProvider
注册自己的RouteRegistrar
。
例
我在routes.php
中添加了自己的资源控制器,如下所示:
Route::resource('photo', 'PhotoController');
因此,我应该有一个PhotoController
来处理此请求。
实现
我们知道,对"/photo"的GET
请求将通过PhotoController@index
方法处理,要修改您的photo:index
操作以photo:root
操作,请将您的ResourceRegistrar
修改为如下所示的内容:
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);
}
}
所以现在GET
对"/photo"的请求将通过PhotoController@root
方法处理。
备忘单
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|
在此处查看ResourceRegistrar
的基本代码。