Bulk actions

You're browsing the documentation for an old version of MoonShine. Consider upgrading your project to MoonShine 2.x.

By default, the table in the MoonShine panel contains only 1 mass action for the elements - deletion. But you can also add your own custom bulk actions

namespace MoonShine\Resources;
 
use MoonShine\Models\MoonshineUser;
use MoonShine\BulkActions\BulkAction;
 
class PostResource extends Resource
{
public static string $model = App\Models\Post::class;
 
public static string $title = 'Articles';
//...
 
public function bulkActions(): array
{
return [
BulkAction::make('Deactivation', function (Model $item) {
$item->update(['active' => false]);
}, 'Deactivated')->icon('app')
];
}
 
//...
}

The first argument is the name of the action. The second argument is a callback with the current element parameter. The third argument is the message that will be displayed after the execution of the action.

# Display method

To display actions as a dropdown list, you can use the showInDropdown method

use MoonShine\BulkActions\BulkAction;
 
//...
public function bulkActions(): array
{
return [
BulkAction::make('Deactivation', function (Model $item) {
$item->update(['active' => false]);
}, 'Deactivated')
->showInDropdown()
];
}
//...

This display method is used by default

To display actions as a horizontal list, you can use the showInLine method

use MoonShine\BulkActions\BulkAction;
 
//...
public function bulkActions(): array
{
return [
BulkAction::make('Deactivation', function (Model $item) {
$item->update(['active' => false]);
}, 'Deactivated')
->showInLine()
];
}
//...

# Confirm the action

To confirm the action, you must use the withConfirm method

use MoonShine\BulkActions\BulkAction;
 
//...
public function bulkActions(): array
{
return [
BulkAction::make('Deactivation', function (Model $item) {
$item->update(['active' => false]);
}, 'Deactivated')
->withConfirm()
];
}
//...

The withConfirm() method can be passed the title and text for the modal window, as well as the title for confirmation button

use MoonShine\BulkActions\BulkAction;
 
//...
public function bulkActions(): array
{
return [
BulkAction::make('Deactivation', function (Model $item) {
$item->update(['active' => false]);
}, 'Deactivated')
->withConfirm('Title', 'Modal content', 'Accept')
];
}
//...

The errorMessage() method allows you to set the text of the error message

use MoonShine\BulkActions\BulkAction;
 
//...
public function bulkActions(): array
{
return [
BulkAction::make('Deactivation', function (Model $item) {
$item->update(['active' => false]);
}, 'Deactivated')
->withConfirm('Title', 'Modal content', 'Accept')
->errorMessage('Fail')
];
}
//...