我的 REST API url 具有以下架构:
Verb Url Method
GET /tasks findAll
GET /tasks/{id} findOne
POST /tasks create
PUT /tasks/{id} update
DELETE /tasks/{id} deleteOne
DELETE /tasks deleteAll
Run Code Online (Sandbox Code Playgroud)
有没有办法覆盖路由资源 Laravel 内置方法(存储、创建、编辑等)的默认方法,并使用单行创建与我的控制器关联的自定义路由?
例如:
Route::resource('/tasks', 'TasksController');
Run Code Online (Sandbox Code Playgroud)
代替:
Route::get('/tasks', 'TasksController@findAll');
Route::get('/tasks/{id}', 'TasksController@findOne');
Route::post('/tasks', 'TasksController@create');
Route::put('/tasks/{id}', 'TasksController@update');
Route::delete('/tasks', 'TasksController@deleteAll');
Route::delete('/tasks/{id}', 'TasksController@deleteOne');
Run Code Online (Sandbox Code Playgroud)
我已经解决了更改 ResourceRegistrar.php 类的这些步骤,这实现了我的要求。(@Thomas Van der Veen 建议):
1)我已经用我想要的方法替换了 $resourceDefaults 数组:
protected $resourceDefaults = ['findAll', 'findOne', 'create', 'update', 'deleteOne', 'deleteAll'];
Run Code Online (Sandbox Code Playgroud)
2)创建执行操作的方法后,删除较旧的方法。
protected function addResourceFindAll($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name);
$action = $this->getResourceAction($name, $controller, 'findAll', $options);
return $this->router->get($uri, $action);
}
protected function addResourceFindOne($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name).'/{'.$base.'}';
$action = $this->getResourceAction($name, $controller, 'findOne', $options);
return $this->router->get($uri, $action);
}
protected function addResourceCreate($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name);
$action = $this->getResourceAction($name, $controller, 'create', $options);
return $this->router->post($uri, $action);
}
protected function addResourceUpdate($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name).'/{'.$base.'}';
$action = $this->getResourceAction($name, $controller, 'update', $options);
return $this->router->put($uri, $action);
}
protected function addResourceDeleteAll($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name);
$action = $this->getResourceAction($name, $controller, 'deleteAll', $options);
return $this->router->delete($uri, $action);
}
protected function addResourceDeleteOne($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name).'/{'.$base.'}';
$action = $this->getResourceAction($name, $controller, 'deleteOne', $options);
return $this->router->delete($uri, $action);
}
Run Code Online (Sandbox Code Playgroud)
就是这样,效果很好!
| 归档时间: |
|
| 查看次数: |
4394 次 |
| 最近记录: |