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
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?
For example:
Route::resource('/tasks', 'TasksController');
Instead of:
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');
I have solved making these steps changing the ResourceRegistrar.php class, this achieve my request. (suggest by @Thomas Van der Veen):
1) I have replaced $resourceDefaults array with my desires methods:
protected $resourceDefaults = ['findAll', 'findOne', 'create', 'update', 'deleteOne', 'deleteAll'];
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);
}
That's it, works very well!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With