How to Add Mass Actions to Datatable
Last updated
Last updated
In QuickAdminPanel tables, you can tick the checkbox on every row, and then click Delete Selected:
That's the only "mass action" available. But you can create more, pretty easily.
You just need to repeat a block of code from index.blade.php file.
Currently, in resources/views/admin/courses/index.blade.php we have this JavaScript code for Delete selected button:
Let's break it down - what is happening here:
Checking @can('course_delete') for permission for this button - read more about roles/permissions here.
Button label comes from translations - see trans() method
We need to assign the URL - what should happen after the click, so we specify route('admin.courses.massDestroy')
We choose button class - btn-danger
We specify the action: first we get the list of record IDs (every row has <tr data-entry-id="xxx">), if that list is empty - we throw error alert that no rows are selected
We ask for confirmation - do you want to delete selected record?
If it's confirmed, we're making AJAX request to the URL we specified in Step 3, and then reload the whole page
That URL is specified in routes/web.php:
Finally, here's how it works in app/Http/Controllers/Admin/CoursesController.php:
For example, let's add another button Publish which will mass-publish the Courses from the table above.
We almost copy-paste the index.blade.php block to a new one, just below the old one:
What I've changed here:
Button Label: publishButtonTrans = 'Publish' (or you can use translations, too)
Different URL: route('admin.courses.massPublish') - we will create it in a minute
Button Class: instead of btn-danger, I specified btn-warning
AJAX Method: instead of 'DELETE' I use simple 'POST'
Notice: if you're using AJAX Datatables module, you need to populate the ids array a bit differently:
And, that's it! We have a button:
To make that button work, we specify the URL in routes/web.php:
Notice: that Route should come before the resource line of Route::resource() for the same Controller, otherwise it may conflict with Resourceful methods and be overridden.
Finally, we implement that massPublish in app/Http/Controllers/Admin/CoursesController.php - almost identical to massDestroy above:
That's it, you have you mass-action!