Skip to content

Instantly share code, notes, and snippets.

@CurtisL
Created August 29, 2019 20:51
Show Gist options
  • Save CurtisL/64fa36a3ee9af379217adc7218825617 to your computer and use it in GitHub Desktop.
Save CurtisL/64fa36a3ee9af379217adc7218825617 to your computer and use it in GitHub Desktop.

Stubbed out concept for how to handle bulk actions procedurally.

Extend the BulkAction class with a minimum of $name, $model and handle() method.

Create a POST able endpoint like applicaitons/bulk-edit/{action}

Post data with an ids key that is an array of ids. optionally post a fields key to include any custom field data to pass along to your handler.

ON the frontend you can handle the success and error responses and toast the message.

On success (for datatables) you can call .draw() on the table var.

<?php
namespace App\Http;
use Illuminate\Http\Request;
class BulkAction
{
public $model;
public $name;
public function __construct()
{
}
function success($msg)
{
return response()->json(['success' => $msg], 200);
}
function error($msg)
{
return response()->json(['error' => $msg], 422);
}
function handleRequest(Request $request)
{
$fields = $request->get('fields');
$ids = $request->get('ids');
if (!$ids) {
return $this->error('No ids selected');
}
$model = app($this->model);
$models = $model->find($ids);
if (is_callable(array($this, 'handle'))) {
return $this->handle($fields, $models);
}
return $this->error('Action has no Handle Method');
}
}
<?php
namespace App\Http\BulkActions;
use App\Http\BulkAction;
class CustomBulkAction extends BulkAction
{
public $name = 'bulk_action_slug';
public $model = 'App\Application'; // model class instance
// action handler, where the magic actually happens
public function handle($fields, $applications)
{
// you could validate the $fields array or whatever beforehand
if (!isset($fields['status'])) {
return $this->error('No status provided');
}
foreach ($applications as $application) {
$application->status = $fields['status'];
$application->save();
}
return $this->success('Applications Updated');
}
}
<?php
class SomeController
{
//... other controller actions ...
public function bulkActions(Request $request)
{
return [
new CustomBulkAction,
];
}
public function bulkEdit(Request $request, $action)
{
foreach ($this->bulkActions($request) as $bulkAction) {
if ($bulkAction->name === $action) {
return $bulkAction->handleRequest($request);
}
}
return response()->json(['error'=> 'Action ' . $action . ' found'], 404);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment