lara-pack / livewire-sweetalert
Livewire Sweetalert
Package info
github.com/bhagaskara/lara-pack-livewire-sweetalert
pkg:composer/lara-pack/livewire-sweetalert
Requires
- livewire/livewire: ^3.0|^4.0
README
This Laravel package provides an easy way to trigger SweetAlert2 notifications from Livewire v3 or v4 components.
Requirements
- PHP ^8.1
- Laravel ^10.0 or ^11.0
- Livewire ^3.0 or ^4.0
- SweetAlert2 (must be installed in your frontend assets)
Installation
You can install the package via composer:
composer require lara-pack/livewire-sweetalert
The package will automatically register its Service Provider.
Frontend Preparation
Ensure you have included the SweetAlert2 library in your main layout (usually app.blade.php).
You can use CDN:
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
Or install it via NPM:
npm install sweetalert2
Usage
You can use the LaraPack\LivewireSweetalert\Alert class inside your Livewire components.
Success / Fail Notifications
Use the success or fail methods to display simple informational messages.
use LaraPack\LivewireSweetalert\Alert; use Livewire\Component; class CreateUser extends Component { public function save() { // Save logic... Alert::success($this, 'Success!', 'User data has been saved.'); } public function handleError() { Alert::fail($this, 'Failed!', 'An error occurred while processing data.'); } }
Confirmation Tool
Use the confirmation method to display a confirmation dialog that triggers other Livewire actions based on the user's choice.
use LaraPack\LivewireSweetalert\Alert; use Livewire\Component; class UserTable extends Component { public function deleteConfirm($id) { Alert::confirmation( $this, Alert::ICON_WARNING, 'Are you sure?', 'Deleted data cannot be recovered!', 'delete', // Event name if confirmed (Yes) 'cancelDelete', // Event name if cancelled (No) 'Yes, delete it!', // Confirmation button text (Optional) 'Cancel' // Cancel button text (Optional) ); } #[On('delete')] public function delete() { // Deletion logic... Alert::success($this, 'Deleted!', 'Data has been successfully deleted.'); } #[On('cancelDelete')] public function cancelDelete() { // Optional: Logic if cancelled } }
How It Works
This package uses middleware to inject a JavaScript script that listens for Livewire events (SwalInfo and SwalConfirm). When you call a method in the Alert class, this package dispatches an event to the frontend which is then caught by the script to display SweetAlert.
License
The MIT License (MIT). Please see License File for more information.