Search code examples
laravelroutescontrollerlaravel-apibulk-delete

ResourceController - BulkDelete


Recently I watched "Cruddy by Design" - Laracon US 2017 and now I'm trying to get rid of any extra methods in my controllers (so I only have index, create, store, show, edit, update and destroy)

Adam Wathan talks about creating new controllers to put those methods in, so for example:

PodcastsController@publish

would become

PublishedPodcastsController@store

So right now my application has these routes:

Route::delete('tags', [TagsController::class, 'bulk_delete']);
Route::resource('tags', TagsController::class);

and I'm not sure how to refactor the bulk_delete method.

An idea I came up with was to rename the TagsController controller into TagController (singular), create a new TagsController (plural), and move there the bulk_delete method, so I would have these routes:

Route::resource('tag', TagController::class); // index, create, store, show, edit, update, destroy
Route::resource('tags', TagsController::class)->only([
    'delete' // delete => bulk_delete
]);

but I'm not sure that I like it.

Is there any other way to fit the bulk_delete method in a ResourceController?


Solution

  • To be honest using something like a TagsController is in my opinion a big no since Laravel is using plural or none plural in his own logic.

    You could add a Request to the destroy method and check for a request value like items, but you still would have to deal with the Object since default it tries to create an object.

    What you could do is post a delete and instead of /{idofdeleteobject} pass a string like /bulk and if the Tag is null since it is not an ID check for an array of object in the request,

    public function(Tag $tag, Request $request) {
        if(!is_null($tag)) {
           return $tag->delete();
        })
       
        if($request->has('bulk') {
           // logic for deleting all bulk
        })
    }