我的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
是否有一种方法可以覆盖路由资源Laravel内置方法的默认方法(存储,创建,编辑等),并创建与我的控制器关联的自定义路由单行?
例如: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建议):
1)我已经替换了$resourceDefaults数组与我的愿望的方法:
protected $resourceDefaults = ['findAll', 'findOne', 'create', 'update', 'deleteOne', 'deleteAll'];
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);
}
就是这样,工作得很好!
你应该看看这里的Laravel文档:https://laravel.com/docs/5.3/controllers#resource-controllers
关于deleteAll动作,Laravel没有提供默认调用。我建议避免这种情况。
要创建一个资源控制器,只需在终端上输入以下命令:
php artisan make:controller TasksController --resource
这将创建一个带有您必须填充的默认CRUD操作的控制器。
然后在routes.php中添加:
Route::resource('tasks', 'TasksController');
您将能够像您描述的那样向服务器发送呼叫。