3

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?

Professor
  • 858
  • 1
  • 9
  • 17

2 Answers2

1

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
    })
}
Marcel Santing
  • 103
  • 1
  • 5
0

No this is basically not a good approach to create as many controllers for same resource.

It is okay if you want to use some functions other than resource. Like if you have

Route::resource('tags', TagsController::class);

So if you need to use bulk-delete method then you can:

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

And you can pass ids in the query params and access them via Request::class in controller.

  • That's exactly what I'm already doing. I want to find out if there's any better way to do it. I do not want to create custom routes, only resources. – Professor May 10 '21 at 11:32
  • But laravel by default don't support any custom method in resource. In your case you definitely needs a custom method for bulk delete, which is not provided by laravel resource. So, in such scenarios it is best to create a custom method and use it, instead of creating an other controller. – Çh Furqan Hämëèd Jūtt May 10 '21 at 15:47