Livewire Alert is a Laravel Livewire package designed to integrate SweetAlert2 notifications seamlessly into Livewire projects. This package simplifies the process of displaying simple, customizable alerts to users, enhancing the interactivity and user experience of your Livewire projects.
You can check the interactive demo here: livewire-alert.laravel.cloud
- PHP 8.1 or higher
- Laravel 10.x or higher
- Livewire 3.x
- Composer
First, require the package with Composer:
composer require jantinnerezo/livewire-alert
Optionally, if you want to customize the global configuration, you can publish the config file:
php artisan vendor:publish --tag=livewire-alert:config
Next, install SweetAlert2 via npm or yan:
NPM
npm install sweetalert2
Yarn
yarn add sweetalert2
After installing SweetAlert2, import it into your resources/js/app.js
file
import Swal from 'sweetalert2'
window.Swal = Swal
If you prefer not to use package manager installation, you can include SweetAlert2 directly via CDN. Add the following script to your Blade layout file (e.g., resources/views/layouts/app.blade.php)
before the closing </body>
tag:
<body>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</body>
Integrate Livewire Alert in your Filament project, simply register the JavaScript asset in the boot method of your AppServiceProvider
in boot
method to import SweetAlert2.
use Filament\Support\Facades\FilamentAsset;
use Illuminate\Support\Facades\Vite;
use Filament\Support\Assets\Js;
public function boot()
{
FilamentAsset::register([
// Local asset build using Vite
Js::make('sweetalert2', Vite::asset('resources/js/sweetalert2.js')),
// Or via CDN
Js::make('sweetalert2', 'https://cdn.jsdelivr.net/npm/sweetalert2@11'),
]);
}
This package provides a convenient Facade that allows you to trigger customizable SweetAlert2-based alerts in your Laravel Livewire application. The Facade uses a fluent interface, enabling you to chain methods to configure your alert before displaying it.
use Jantinnerezo\LivewireAlert\Facades\LivewireAlert;
public function save()
{
LivewireAlert::title('Changes saved!')->success()->show();
}
LivewireAlert::title('Item Saved')
->text('The item has been successfully saved to the database.')
->success()
->show();
LivewireAlert::title('Success')->success();
LivewireAlert::title('Error')->error();
LivewireAlert::title('Warning')->warning();
LivewireAlert::title('Info')->info();
LivewireAlert::title('Question')->question();
The position()
method allows you to specify where the alert appears on the screen. You can use either the Position enum for type safety or a plain string for flexibility.
Leverage the Position enum for predefined, type-safe options:
use Jantinnerezo\LivewireAlert\Enums\Position;
LivewireAlert::title('Question')
->position(Position::Center)
->question()
->show();
Alternatively, you can pass a string directly, but it must exactly match one of the Position
enum values, See: Position enum.
LivewireAlert::title('Question')
->position('center')
->question()
->show();
Create a toast-style alert with the toast()
method:
LivewireAlert::title('Welcome!')
->text('You have logged in successfully.')
->info()
->toast()
->position('top-end')
->show();
The timer()
method sets an auto-dismiss timer for the alert, specifying how long (in milliseconds) the alert remains visible before closing automatically.
Pass an integer representing the duration in milliseconds:
LivewireAlert::title('Success')
->text('Operation completed successfully.')
->success()
->timer(3000) // Dismisses after 3 seconds
->show();
The LivewireAlert package provides methods to add and customize buttons in your alerts: withConfirmButton()
, withCancelButton()
, and withDenyButton()
. Each button can trigger specific events, handled via onConfirm()
, onDeny()
, or onDismiss()
, allowing you to execute custom logic in your Livewire component.
LivewireAlert::title('Save?')
->withConfirmButton('Yes, Save')
->show();
LivewireAlert::title('Hey cancel')
->withCancelButton('Cancel')
->show();
LivewireAlert::title('Are you do you want to do it?')
->withDenyButton('No')
->show();
Alternatively, you can use confirmButtonText()
, cancelButtonText()
, and denyButtonText()
to set the text after enabling the buttons with withConfirmButton()
, withCancelButton()
, or withDenyButton()
without text:
LivewireAlert::title('Save?')
->withConfirmButton() // Enables button with default text
->confirmButtonText('Yes')
->withDenyButton() // Enables button with default text
->denyButtonText('No')
->withCancelButton() // Enables button with default text
->cancelButtonText('Cancel')
->show();
You can customize the appearance of buttons by setting their colors using the confirmButtonColor()
, cancelButtonColor()
, and denyButtonColor()
methods. These methods accept a color value (e.g., color names, hex codes, or CSS-compatible strings) to style the respective buttons.
LivewireAlert::title('Save?')
->confirmButtonColor('green')
->withDenyButton('red')
->withCancelButton('blue')
->show();
Each button can trigger a corresponding event when clicked, allowing you to handle user interactions in your Livewire component.
LivewireAlert::title('Save?')
->withConfirmButton('Save')
->onConfirm('saveData', ['id' => $this->itemId])
->show();
public function saveData($data)
{
$itemId = $data['id'];
// Save logic
}
LivewireAlert::title('Delete?')
->withConfirmButton('Delete')
->withCancelButton('Keep')
->onDismiss('cancelDelete', ['id' => $this->itemId])
->show();
public function cancelDelete($data)
{
$itemId = $data['id'];
// Cancel logic
}
LivewireAlert::title('Update?')
->withConfirmButton('Update')
->withDenyButton('Discard')
->onDeny('discardChanges', ['id' => $this->itemId])
->show();
public function discardChanges($data)
{
$itemId = $data['id'];
// Discard logic
}
LivewireAlert::title('Process File')
->text('What would you like to do?')
->question()
->withConfirmButton('Save')
->withCancelButton('Cancel')
->withDenyButton('Delete')
->onConfirm('saveFile', ['id' => $this->fileId])
->onDeny('deleteFile', ['id' => $this->fileId])
->onDismiss('cancelAction', ['id' => $this->fileId])
->show();
The asConfirm()
method configures the alert as a confirmation dialog with a predefined options. It automatically applies a question icon, adds confirm and deny buttons with default text from the configuration, and disables the auto-dismiss timer, making it ideal for scenarios requiring explicit user input.
LivewireAlert::title('Are you sure?')
->text('Do you want to proceed with this action?')
->asConfirm()
->show();
Combine with onConfirm()
and onDeny()
to handle user responses:
LivewireAlert::title('Delete Item')
->text('Are you sure you want to delete this item?')
->asConfirm()
->onConfirm('deleteItem', ['id' => $this->itemId])
->onDeny('keepItem', ['id' => $this->itemId])
->show();
public function deleteItem($data)
{
$itemId = $data['id'];
// Delete logic
}
public function keepItem($data)
{
$itemId = $data['id'];
// Keep logic
}
The LivewireAlert package allows you to add input fields to alerts using the withOptions()
method, leveraging SweetAlert2’s input capabilities. This is useful for collecting user input (e.g., text, selections) directly within the alert, with the input value returned via event handlers like onConfirm()
.
Use withOptions()
to pass an array containing SweetAlert2 input options. Common input types include text
, email
, password
, number
, textarea
, select
, radio
, checkbox
, and file
.
Add a simple text input:
LivewireAlert::title('Enter Your Name')
->withOptions([
'input' => 'text',
'inputPlaceholder' => 'Your name here',
])
->withConfirmButton('Submit')
->onConfirm('saveName')
->show();
public function saveName($data)
{
$name = $data['value']; // User’s input from the text field
// Save the name
}
Select Input Example
LivewireAlert::title('Choose an Option')
->withOptions([
'input' => 'select',
'inputOptions' => [
'small' => 'Small',
'medium' => 'Medium',
'large' => 'Large',
],
'inputPlaceholder' => 'Select a size',
])
->withConfirmButton('Confirm')
->onConfirm('processSelection')
->show();
public function processSelection($data)
{
$size = $data['value']; // Selected value (e.g., 'small')
// Process the selection
}
When an input is present, the $data
parameter in event methods (e.g., onConfirm()
, onDeny()
) includes a value property containing the user’s input. This value depends on the input type:
- Text, email, password, number, textarea: The entered string or number.
- Select, radio: The selected option’s key.
- Checkbox: true or false.
- File: The file data (if applicable).
Need to flash alerts across requests? In this package you can leverage Laravel’s session flashing alerts and display them in your Livewire components. This feature, inspired by version 3’s simplicity, gives you full freedom to define your own session keys and structure, allowing tailored flash alerts that appear automatically (e.g., on mount())
after actions like redirects.
public function mount()
{
if (session()->has('saved')) {
LivewireAlert::title(session('saved.title'))
->text(session('saved.text'))
->success()
->show();
}
}
public function changesSaved()
{
session()->flash('saved', [
'title' => 'Changes Saved!',
'text' => 'You can safely close the tab!',
]);
$this->redirect('/dashboard');
}
The withOptions()
method allows you to extend the alert’s configuration with any SweetAlert2-compatible options, giving you full control to customize its appearance, behavior, or functionality beyond the built-in methods. This is ideal for advanced use cases like adding inputs, modifying styles, or setting custom SweetAlert2 features.
LivewireAlert::title('Custom Alert')
->text('This alert has a unique style.')
->success()
->withOptions([
'width' => '400px',
'background' => '#f0f0f0',
'customClass' => ['popup' => 'animate__animated animate__bounceIn'],
'allowOutsideClick' => false,
])
->show();
For a comprehensive guide to customization and available configuration options, please refer to the SweetAlert2 documentation.
Who said you can only use the Facade? With this package, you can also inject the Jantinnerezo\LivewireAlert\LivewireAlert
class directly into your Livewire component methods via dependency injection. This approach lets you access the alert functionality within the context of your component, offering a clean alternative to the Facade syntax.
use Jantinnerezo\LivewireAlert\LivewireAlert;
public function save(LivewireAlert $alert)
{
$alert->title('Success!')
->text('What would you like to do?')
->question()
->withConfirmButton('Save')
->withCancelButton('Cancel')
->withDenyButton('Delete')
->onConfirm('saveFile', ['id' => $this->fileId])
->onDeny('deleteFile', ['id' => $this->fileId])
->onDismiss('cancelAction', ['id' => $this->fileId])
->show();
}
All methods remain available, and you can chain them fluently just like with the Facade!
If you’re seeking documentation for livewire-alert v3, note that the last release of the version 3 series was v3.0.3, available on GitHub at v3.0.3 Released on March 11, 2024, this version supports Livewire 3 and latest Laravel 12 and includes features like basic alert functionality with the LivewireAlert
trait.
This release, however, is a major refactor of the package, introducing a new architecture and enhanced features (like the fluent Facade interface and dependency injection). As a result, the documentation below focuses on v4.
For v3-specific usage:
composer require jantinnerezo/livewire-alert:^3.0
For ongoing projects, I recommend upgrading to v4.0 to take advantage of the improved API and feature set detailed in this documentation.
composer test
Please see CONTRIBUTING for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.