realrashid/sweet-alert
Laravel wrapper for SweetAlert2 that makes it easy to show stylish alert, toast, and confirmation dialogs. Flash messages from controllers or middleware, with helpers for success/error/warning/info, custom options, and Blade support for quick integration.
Installation:
composer require realrashid/sweet-alert
Publish the config (optional but recommended):
php artisan vendor:publish --provider="RealRashid\SweetAlert\SweetAlertServiceProvider" --tag="config"
Load Assets:
Add to your resources/views/layouts/app.blade.php (or equivalent):
@include('sweetalert::alert')
First Usage: In a controller or route:
use RealRashid\SweetAlert\Facades\Alert;
// Basic success alert
Alert::success('Success!', 'Your action was completed.');
Or in Blade:
@alert('success', 'Success!', 'Your action was completed.')
// In your controller
public function store(Request $request) {
$validated = $request->validate([...]);
try {
// Save data
Alert::success('Record saved', 'Your data has been saved successfully.');
} catch (\Exception $e) {
Alert::error('Error', 'Failed to save data: ' . $e->getMessage());
}
return back();
}
Flash Messaging Pattern:
// Redirect with flash alert
return redirect()->route('dashboard')
->withSuccess('Profile updated', 'Your profile has been updated successfully.');
Dynamic Alerts:
// Conditional alerts
if ($user->exists) {
Alert::success('User created', 'New user added to the system.');
} else {
Alert::error('Error', 'Failed to create user.');
}
Reusable Alert Components:
<!-- resources/views/components/alert.blade.php -->
@if(session('success'))
@alert('success', session('success.title'), session('success.message'))
@endif
Inline Alerts:
@alert('warning', 'Confirm Action',
'Are you sure you want to delete this item?',
['showConfirmButton' => true, 'showCancelButton' => true]
)
// app/Http/Middleware/HandleInertiaRequests.php
public function terminate($request, $response) {
if ($response->getStatusCode() === 404) {
Alert::warning('Page Not Found', 'The requested resource could not be found.');
}
}
// In a controller
Alert::toast('New Message', 'You have a new notification', 'top-right');
// With custom styling
Alert::toast('Update Available', 'A new version is ready!')
->timerProgressBar()
->position('top-left');
// In Blade
@alert('question', 'Delete Item',
'Are you sure you want to delete this item?',
[
'showConfirmButton' => true,
'showCancelButton' => true,
'confirmButtonText' => 'Delete',
'cancelButtonText' => 'Cancel',
'reverseButtons' => true,
'focusConfirm' => false,
'focusCancel' => true,
'preConfirm' => 'return confirm("This action cannot be undone.")'
]
)
// In config/sweet-alert.php
'theme' => 'dark', // or 'light', 'custom'
// Custom CSS classes
Alert::success('Title', 'Message')
->customClass('custom-alert')
->width('400px')
->padding('2rem');
Missing Assets:
@include('sweetalert::alert') is in your layout.Facade Not Found:
composer dump-autoload
php artisan optimize:clear
Configuration Overrides:
config/sweet-alert.php may override per-alert settings. Use config() helper to check:
$defaultPosition = config('sweet-alert.default_toast_position');
Blade Compilation Issues:
@alert in Blade, escape dynamic content:
@alert('success', '{{ $title }}', '{{ $message }}')
Check Console: SweetAlert2 logs errors to the browser console. Look for:
Uncaught ReferenceError: Swal is not defined
(Fix: Ensure JS is loaded before usage.)
IDE Support: Use @method PHPDoc annotations (added in v7.3.2) for autocompletion:
Alert::success('Title', 'Message')->timer(3000);
'load_js' => 'auto' in config to load SweetAlert only when needed.'cdn' => true) to reduce asset size.Custom Methods: Create a macro in a service provider:
Alert::macro('customAlert', function($title, $message) {
return $this->success($title, $message)
->timerProgressBar()
->customClass('my-custom-alert');
});
Middleware Integration:
Extend the SweetAlertMiddleware to add custom logic:
public function handle($request, Closure $next) {
if ($request->wantsJson()) {
Alert::json('Info', 'This is a JSON response.');
}
return $next($request);
}
Theming System: Override default themes by publishing assets:
php artisan vendor:publish --provider="RealRashid\SweetAlert\SweetAlertServiceProvider" --tag="public"
Then modify public/vendor/sweetalert/css/sweetalert2.css.
Flash Data Persistence: Flash alerts persist only for the next request. For multi-step forms, use sessions:
session(['alert' => ['type' => 'success', 'title' => 'Title', 'message' => 'Message']]);
Livewire/Alpine Integration: Trigger alerts from frontend:
// Alpine.js
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('alerts', () => ({
showSuccess() {
@this.$wire.emit('showAlert', {
type: 'success',
title: 'Success',
message: 'Action completed'
});
}
}));
});
</script>
In Livewire:
public function showAlert($data) {
Alert::success($data['title'], $data['message']);
}
Testing: Mock alerts in PHPUnit:
$this->expectsEvents(AlertEvent::class);
Alert::success('Test', 'Message');
$this->assertEventDispatched(AlertEvent::class);
How can I help you explore Laravel packages today?