Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Sweetalert Laravel Package

wavey/sweetalert

SweetAlert for Laravel: a Blade component and PHP helper to fire Toastr-style SweetAlert2 notifications from your controllers and views, with configurable icons, positions, timers, and confirmation dialogs, plus support for queued alerts across redirects.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Install the package:
    composer require wavey/sweetalert
    
  2. Publish the config (and optionally the views) so you can tune defaults:
    php artisan vendor:publish --provider="Wavey\Sweetalert\SweetalertServiceProvider"
    
    You'll get config/sweetalert.php with keys for the theme, CDN usage, default timer, button labels, and the Blade view used to render the payload.
  3. Include the package's Blade partial in your layout, right before </body> and after any layout-level scripts. It reads a session flash and emits the Swal.fire(...) calls:
    @include('sweetalert::sweetalert')
    
    (Check the README of the version you installed — the include name is the one thing that has moved between releases.)
  4. First use case: flash a success message from a controller after a redirect.
    use Wavey\Sweetalert\Facades\Sweetalert;
    
    public function store(Request $request)
    {
        // ... validate and create
        Sweetalert::alert()->success('Saved', 'The record was created.');
        return redirect()->route('records.index');
    }
    
  5. Confirm it renders by hitting that route in a browser — the alert should fire on page load from the flash bag. If nothing shows, confirm the partial is actually included in the layout and that your session driver is not array.

Implementation Patterns

Redirect-after-write (the primary pattern). Because the package writes into the session and renders on the next request, treat it as a flash-message channel. Controllers stay clean: do the work, call Sweetalert::alert()->success(...), return a redirect. Avoid calling it on requests that render a full response directly — the payload won't be consumed properly in some setups (see Gotchas).

Toasts for background actions. Use the toast variant for non-blocking confirmations (auto-save, copy-to-clipboard, background jobs). Configure the default timer once in config/sweetalert.php and override per call:

Sweetalert::toast('Draft saved')->timer(2500);

Confirmation dialogs with a follow-up URL. The package supports a "confirm" style alert that redirects to a URL when the user clicks the confirm button. This is the cleanest way to wire "Delete" buttons without writing JavaScript by hand:

Sweetalert::confirm('Delete record?', 'This cannot be undone.', route('records.destroy', $record));

For destructive actions, pair this with a POST/DELETE route and CSRF, not a GET link.

Chaining icon helpers. Use alert()->success() / error() / warning() / info() consistently across the app so the icon vocabulary stays uniform. Wrap this in a small AlertService or trait (flashSuccess(), flashError($e)) so views and Livewire components don't import the facade directly.

Integrating with existing flash systems. If you already push to session()->flash('status', ...) in an Inertia/Livewire app, don't double up. Pick one channel — the package reads its own session key, so mixing it with your own flash partial leads to orphaned payloads that fire on an unrelated later page. Either migrate fully to Sweetalert:: calls or keep them separate.

Form validation feedback. On ValidationException, show a warning alert from the exception handler or a form request, then redirect back — the message lands next to the field errors when the page re-renders.

Wrapper for testability. Since the facade is stateless sugar over the session, wrap it:

class Alerts
{
    public function success(string $title, string $text = ''): void
    {
        Sweetalert::alert()->success($title, $text);
    }
}

Then swap the implementation to a null object in tests.

Gotchas and Tips

  • Session dependency. The whole mechanism is a flash bag write plus a view read. If your app uses SESSION_DRIVER=array (common in CI), alerts will silently never render. In phpunit.xml, prefer asserting on the session key rather than the browser behaviour.
  • Rendering order matters. The partial must run after the session has the payload — i.e., on the request after the one that called Sweetalert::alert(). If you call it and render a view in the same request you'll get an alert that fires twice, or not at all, depending on how the flash is consumed. Stick to redirects.
  • The bundle can be stale relative to SweetAlert2. Last release is 2022-11-19, and SweetAlert2's API has moved on (toast, timerProgressBar, option names). If you need newer SweetAlert2 features, either pin the CDN version in config/sweetalert.php to one the package was tested against, or drop the CDN bundle and import SweetAlert2 yourself via Vite, keeping only the session-to-payload rendering from the package.
  • Publish the view to customise. Almost every "it doesn't look right" complaint is really a theming problem. Publish the view (--tag=views) and adjust the theme, confirmButtonText, cancelButtonText, and timer keys in the config rather than fighting the defaults inline.
  • Multiple alerts queue up. Each Sweetalert::alert() call appends; they don't replace each other. Useful for stacking a success toast plus an error, but easy to accidentally fire three identical alerts from a loop. Keep one call per outcome.
  • CSP and defer. If your Content Security Policy disallows inline scripts, the partial's inline Swal.fire calls will be blocked without an obvious console hint unless you're watching for CSP violations. Either add a nonce to the partial or move the calls into a small external file you include yourself.
  • Livewire / Inertia. Inertia responses don't re-render Blade layouts, so the partial never runs — the alert sits in the session until the next full page load. For Livewire, dispatch a browser event (->dispatch('sweetalert', ...)) and have a small JS listener call Swal.fire directly. Don't route Livewire notifications through this package.
  • Testing. Assert on the session instead of the DOM:
    $response->assertSessionHas('sweetalert');
    
    or, if you wrap the facade, assert that your Alerts service received the call — cleaner and immune to the package's internal session key.
  • Extension points are thin. There's no event or formatter hook — the fastest customisation is publishing the Blade view and the config. If you need structured payloads (e.g., passing an array of actions), you'll end up editing the published view directly. Budget for that rather than hoping for a config flag.
  • Version pinning beats upgrading. With a single maintained release from 2022 and no dependents, treat it as a thin convenience layer, not infrastructure you'll get upstream fixes for. Pin the version in composer.json and keep your own notes on the SweetAlert2 version you tested with, so a future composer update doesn't quietly change dialog behaviour.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
cgv/localized-resource