sweetalert2/laravel
A Laravel integration for SweetAlert2 that makes it easy to flash session alerts and trigger toast or dialog notifications from your backend using a simple facade or helper.
Start by reading the package README and the service provider source in vendor/sweetalert2/laravel/. The public surface is intentionally small: a service provider, a facade/helper, optional config/views, and some way to render SweetAlert2 assets in a Blade layout. Confirm the exact facade/helper name and Blade include/directive before wiring it into multiple layouts. As of 1.4.3, alerts are delivered via session()->flash(), so they are intended to survive exactly one subsequent request — keep that lifecycle in mind from the start.
Minimal setup:
composer require sweetalert2/laravel:^1.4.3
php artisan vendor:publish --provider="SweetAlert2\Laravel\SweetAlertServiceProvider"
<body>.First useful case: post-redirect success messaging after a form submit.
use SweetAlert2\Laravel\Facades\SweetAlert;
public function store(StorePostRequest $request)
{
$post = Post::create($request->validated());
SweetAlert::success('Saved', 'Your post was created.');
return redirect()->route('posts.index');
}
If the package’s API differs, keep the same pattern: build the alert server-side, redirect, and let the layout render it once from the flashed session payload.
Use it as a thin notification layer, not an application concern. Keep controllers clean by wrapping alert creation in a small notifier service or base controller method.
class Notifier
{
public function saved(string $subject): void
{
SweetAlert::success('Saved', "{$subject} was saved successfully.");
}
}
This gives you one place to change if the package API changes, and one place to fake in tests.
Prefer flash-style post-redirect alerts for CRUD. The best day-to-day use is after store, update, destroy, login, logout, or email verification. Do not fire SweetAlert2 directly from every controller response; let the redirect complete, then show the alert in the next page load. That avoids coupling alert JS to response generation, and since 1.4.3 the flash semantics match Laravel’s normal one-request flash behavior.
Centralize alert types. Define a small set of consistent alerts: success, error, warning, info, and toast. Avoid one-off titles/text scattered across controllers. For validation failures, keep Laravel’s normal error bag and use SweetAlert2 only for a summary or non-blocking toast; do not replace inline field errors.
Use toasts for non-blocking feedback and modals for decisions. A success toast is usually enough for background actions. Use SweetAlert2 confirm dialogs only for destructive actions where you need an explicit “are you sure?” step. Keep the actual authorization and deletion on the server.
For destructive confirmations, submit a real form after confirmation. Do not rely on a JavaScript-only confirm as security. The pattern should be:
@csrf and @method('DELETE').Use it with server-rendered Blade first. The package is most natural in classic Laravel + Blade apps. If you use Livewire, Inertia, or a SPA, verify compatibility early. In those stacks it is often simpler to call Swal.fire() directly from your frontend bundle or dispatch a browser event rather than routing everything through a Laravel flash package.
Testing pattern: assert the server-side state, not the JavaScript. Because the package now flashes, assert the alert payload on the redirect response; a follow-up request consumes it.
$response = $this->post('/posts', $data);
$response->assertRedirect('/posts');
$response->assertSessionHas('sweet_alert');
// Optional: assert it is gone on a subsequent request
$this->get('/posts')->assertSessionMissing('sweet_alert');
Adjust the session key to whatever the package actually uses.
Integration tip: include the package’s Blade partial/directive exactly once. If you have separate guest and authenticated layouts, add it to both or extract a shared layout partial. Duplicate includes can cause double alerts or duplicate script loading. Because alerts are flashed in 1.4.3+, a missing include silently loses the alert on the next request rather than leaving it pending.
This is a low-adoption package. With few stars and no dependents, treat it as a convenience wrapper rather than core infrastructure. Pin the version in composer.json, read the source before upgrading, and be prepared to replace it with a few lines of Blade plus Swal.fire() if the API becomes inconvenient. In particular, stay on 1.4.3 or later to benefit from the flash fix; earlier 1.4.x versions could leave alerts in the session longer than intended.
Check how assets are loaded. The package may use a CDN, published assets, or expect SweetAlert2 to already be present. Verify this in staging and production. If you have a strict Content Security Policy, a CDN script may be blocked. Prefer local assets or add the correct CSP entries.
Escape user-controlled strings. Alert titles and text often come from user data or validation messages. 1.4.3 hardens Swal JSON rendering against invalid UTF-8 input, which is a welcome defensive fix — but it is still your responsibility not to build alert JavaScript with raw {!! !!} output. Keep using the facade/helper, and if you publish the Blade view, audit it for escaping and JSON-encoding. Invalid UTF-8 hardening means bad input should not break the JSON payload; it does not replace HTML escaping discipline.
Session alerts are one-shot as of 1.4.3. The package now calls session()->flash(), so each alert is consumed on the next request. This fixes the previous risk of alerts lingering and appearing later on an unrelated page. The failure mode has flipped: if the target layout is missing the include, the flash is consumed and the alert is silently lost. Verify the include is in the layout actually being rendered for the redirect target.
Multiple alerts need a deliberate policy. Flash semantics make this slightly clearer but do not eliminate the question: if two pieces of code set alerts before one redirect, one may overwrite the other depending on whether the package queues or uses a single session key. Verify the behavior in the source. For multi-step workflows, either queue an array explicitly or show only the most important message.
Multi-tab still has edge cases. A flashed alert is consumed by whichever tab issues the next request. If a user submits a form in one tab and then navigates in another, the alert may appear in the “wrong” tab. Keep alerts short-lived (which flash now enforces) and avoid storing sensitive data in them.
Do not use client-side alerts for validation or security. SweetAlert2 is presentation only. Laravel validation, authorization policies, CSRF protection, and database constraints still do the real work.
Livewire and Inertia need extra care. A package that injects a script into a Blade response may not work after a Livewire navigation or Inertia visit. The flash fix does not change that: the alert may be consumed by a response that never renders the package’s script. In those cases, use the frontend SweetAlert2 package directly and trigger it from the component/page lifecycle.
Debugging checklist: view page source for the rendered script, check the browser console for SweetAlert2 errors, confirm the asset URL loads, inspect the session for the expected alert payload on the redirect response, verify the payload is gone on the follow-up request, and verify the Blade include is present in the layout actually being used.
Extension point: if the package publishes views or config, prefer overriding the published Blade partial or wrapping the facade in your own notifier over editing vendor files. That keeps upgrades predictable and makes alerts easy to disable or swap in tests.
How can I help you explore Laravel packages today?