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 assets (optional, if using custom themes or CDN):
php artisan vendor:publish --provider="RealRashid\SweetAlert\SweetAlertServiceProvider"
First Use Case: Trigger a success alert in a controller:
use RealRashid\SweetAlert\Facades\Alert;
public function store(Request $request) {
Alert::success('Success!', 'Your data has been saved.');
return back();
}
Where to Look First:
config/sweetalert.php (default config, themes, CDN settings)resources/views/vendor/sweetalert/ (published views)// Facade
Alert::error('Error', 'Something went wrong.');
Alert::warning('Warning', 'This action cannot be undone.');
// Helper
alert()->info('Info', 'This is an informational message.');
public function update(Request $request, $id) {
try {
$model = Model::findOrFail($id);
$model->update($request->all());
alert()->success('Updated', 'Record updated successfully.');
} catch (\Exception $e) {
alert()->error('Error', $e->getMessage());
}
return back();
}
public function show($id) {
$model = Model::findOrFail($id);
Alert::info(
'User Details',
"Name: {$model->name}<br>Email: {$model->email}",
'html'
);
return view('profile');
}
// Default position (configurable)
toast('Saved!', 'success');
// Custom position
toast('Updated!', 'info')->position('top-right');
public function destroy($id) {
Alert::question(
'Delete Confirmation',
'Are you sure you want to delete this item?',
function () {
Model::destroy($id);
toast('Deleted!', 'success');
},
function () {
toast('Cancelled', 'info');
}
);
return back();
}
Create a middleware to flash alerts on redirect:
// app/Http/Middleware/AlertMiddleware.php
public function handle($request, Closure $next) {
if ($request->session()->has('alert')) {
$alert = $request->session()->get('alert');
Alert::make($alert['type'], $alert['title'], $alert['message']);
$request->session()->forget('alert');
}
return $next($request);
}
Create a custom Blade directive for reusable alerts:
// app/Providers/BladeServiceProvider.php
Blade::directive('alert', function ($expression) {
return "<?php echo RealRashid\SweetAlert\Facades\Alert::make($expression); ?>";
});
Usage:
@alert(['success', 'Title', 'Message'])
For API responses, use Laravel's response()->json() with a meta field:
return response()->json([
'success' => false,
'message' => 'Validation failed',
'errors' => $validator->errors(),
'meta' => [
'alert' => ['error', 'Validation Error', 'Please check the form.'],
]
]);
Set a default theme in .env:
SWEET_ALERT_THEME=bootstrap-4
Or override per alert:
Alert::make('success', 'Title', 'Message')->theme('material-ui');
Extend the package by publishing assets and modifying:
php artisan vendor:publish --tag=sweetalert-assets
Edit resources/views/vendor/sweetalert/sweetalert.blade.php to add custom options.
Facade vs Helper Confusion:
Alert::success('Title', 'Message')alert()->success('Title', 'Message')Session Flashing:
session()->flash() won’t work directly. Use middleware or redirect with with():
return redirect()->route('home')->with([
'alert' => ['success', 'Success', 'Operation completed.'],
]);
CDN Loading Issues:
config/sweetalert.php. Test with:
Alert::cdn('https://cdn.jsdelivr.net/npm/sweetalert2@11');
Theme Overrides:
.env apply globally. Override per alert with:
Alert::make('Title', 'Message')->theme('dark');
JavaScript Conflicts:
// config/sweetalert.php
'auto_load' => true,
Check Published Assets:
public/vendor/sweetalert/ exists after publishing assets. Clear cache if missing:
php artisan view:clear
php artisan cache:clear
Inspect Network Requests:
F12) and check if SweetAlert2 scripts are loaded. Look for 404 errors.Log Alert Config:
Alert::success('Title', 'Message');
\Log::debug('SweetAlert Config:', [
'config' => \RealRashid\SweetAlert\Facades\Alert::getConfig(),
]);
Disable Middleware:
// app/Http/Kernel.php
protected $middleware = [
// Remove or comment out:
// \RealRashid\SweetAlert\Middleware\SweetAlertMiddleware::class,
];
Custom Alert Types:
Create a new alert type by extending the ToSweetAlert class:
// app/Extensions/CustomAlert.php
namespace App\Extensions;
use RealRashid\SweetAlert\ToSweetAlert;
class CustomAlert extends ToSweetAlert {
public function custom($title, $message) {
$this->title = $title;
$this->text = $message;
$this->type = 'custom';
$this->timer = 10000;
return $this;
}
}
Register in SweetAlertServiceProvider:
$this->app->bind('custom.alert', function () {
return new \App\Extensions\CustomAlert();
});
Dynamic Themes: Fetch themes dynamically from a database:
$theme = Theme::find($request->theme_id)->name;
Alert::make('Title', 'Message')->theme($theme);
Event-Based Alerts: Trigger alerts on events:
// app/Providers/EventServiceProvider.php
protected $listen = [
'user.created' => [
function ($user) {
Alert::success('User Created', "Welcome, {$user->name}!");
},
],
];
Localization: Override SweetAlert2’s text via config:
// config/sweetalert.php
'text' => [
'confirm' => 'Are you sure?',
'cancel' => 'Cancel',
'ok' => 'OK',
],
Performance Optimization:
// config/sweetalert.php
'auto_load' => env('APP_ENV') !== 'production',
How can I help you explore Laravel packages today?