问题描述
我的REST API网址具有以下架构:
I have this schema for my REST API urls:
Verb Url Method
GET /tasks findAll
GET /tasks/{id} findOne
POST /tasks create
PUT /tasks/{id} update
DELETE /tasks/{id} deleteOne
DELETE /tasks deleteAll
是否有一种方法可以替代Route Resource Laravel内置方法(存储,创建,编辑等...)的默认方法,并单行创建与控制器关联的自定义路由?
Is there a way for override the default method of Route Resource Laravel built-in methods (store,create,edit etc...) and create with a single line my custom route associated with my controller?
例如:
Route::resource('/tasks', 'TasksController');
代替:
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');
推荐答案
我已经解决了更改ResourceRegistrar.php类的这些步骤,从而实现了我的要求. (@Thomas Van der Veen建议):
I have solved making these steps changing the ResourceRegistrar.php class, this achieve my request. (suggest by @Thomas Van der Veen):
1)我已将$ resourceDefaults数组替换为我的desires方法:
1) I have replaced $resourceDefaults array with my desires methods:
protected $resourceDefaults = ['findAll', 'findOne', 'create', 'update', 'deleteOne', 'deleteAll'];
2)创建执行动作的方法后,删除较旧的对象.
2) After I have create the methods which execute the actions, deleting the olders.
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);
}
就是这样,效果很好!
这篇关于如何覆盖laravel资源路由默认方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!