Skip to content

Dialogs · Open source

Laravel SweetAlert2

SweetAlert2 popups, toasts and confirm dialogs from Laravel controllers, Livewire and Alpine, plus styled wire:confirm and dialogs you can await.

Laravel 12 and 13 PHP 8.3+ v1.1.1 Free · MIT
Laravel SweetAlert2: SweetAlert2 popups, toasts and confirm dialogs from Laravel controllers, Livewire and Alpine, plus styled wire:confirm and dialogs you can await.

What it solves

Showing a popup after a controller redirects, or asking for confirmation before a delete button runs, usually means writing your own JavaScript and passing data through the session by hand.

Queue popups from a controller and they show on the next page, even after more than one redirect. A data-swal-confirm attribute puts a confirm dialog in front of any link, button or form, and Livewire and Alpine can show popups without a page load. Livewire's existing wire:confirm opens a SweetAlert2 dialog with no markup change, and await $swal.confirm() returns the answer.

  • Flash one or several popups from a controller; they show in order on the next page
  • Popups survive more than one redirect
  • data-swal-confirm on links, buttons, forms, wire:click and wire:submit
  • Livewire's wire:confirm and wire:confirm.prompt open SweetAlert2 dialogs with no markup change; opt out with 'livewire_confirm' => false or data-swal-native
  • Promise dialogs: await $swal.confirm(), prompt() and alert() in Alpine, or window.LaravelSwal in plain JavaScript
  • $this->swal() in Livewire and a sweetalert2 event in Alpine, with wire:navigate support
  • Titles rendered as text and button labels escaped
  • SweetAlert2 11 from a pinned jsDelivr URL with SRI, and Laravel's CSP nonce on every script
A Posts table with three titles and red Delete buttons, dimmed behind a SweetAlert2 warning dialog with an exclamation icon, the title Delete this post?, the text This cannot be undone., and Yes and Cancel buttons with Cancel focused. Behind the dialog, a code strip starts with <button wire:click="delete" wire:confirm.
A Posts table with three titles and red Delete buttons, dimmed behind a SweetAlert2 warning dialog with an exclamation icon, the title Delete this post?, the text This cannot be undone., and Yes and Cancel buttons with Cancel focused. Behind the dialog, a code strip starts with <button wire:click="delete" wire:confirm.

Install

Requires PHP 8.3+ and Laravel 12 and 13.

composer require amjadiqbal/laravel-sweetalert2

Usage

use AmjadIqbal\SweetAlert2\Facades\SweetAlert2;

// In a controller
SweetAlert2::success('Invoice sent', 'We emailed it to the client.');

return redirect()->route('invoices.index');

// Once, in your layout: <x-sweetalert2 />

Setup

Add the component once to your layout, just before </body> (or use @sweetalert2). Publishing the config is optional.

  1. 1 composer require amjadiqbal/laravel-sweetalert2
  2. 2 Add <x-sweetalert2 /> to your layout.
  3. 3 php artisan vendor:publish --tag=sweetalert2-config

From a controller

Every method returns a fluent builder and changes are saved automatically. Popups queued in one request show in order on the next page that renders <x-sweetalert2 />, and only once.

SweetAlert2::success('Saved', 'Your profile is up to date.');
SweetAlert2::toast('Copied to clipboard');

SweetAlert2::success('Order placed', 'We will email you a receipt.')
    ->timer(4000)
    ->position('top')
    ->confirmButton('Great!');

swal('Saved', 'Your profile is up to date.', 'success');

Confirm before an action

Add data-swal-confirm to a link, a button or a form. The action only runs if the user confirms. If SweetAlert2 has not loaded, the browser's own confirm() is used instead. data-swal-text, data-swal-icon, data-swal-confirm-button and data-swal-cancel-button change the dialog.

<form method="POST" action="{{ route('posts.destroy', $post) }}" data-swal-confirm="Delete this post?"
      data-swal-text="This cannot be undone." data-swal-confirm-button="Yes, delete it">
    @csrf @method('DELETE')
    <button>Delete</button>
</form>

<button wire:click="archive" data-swal-confirm="Archive this project?">Archive</button>

Livewire wire:confirm, styled

With the package installed, Livewire's own wire:confirm and wire:confirm.prompt open a SweetAlert2 dialog instead of the browser's confirm() and prompt(). The markup stays as it is. Browser-tested with Livewire 3.8.11 and 4.4.8.

  • Livewire's rules are kept: an empty wire:confirm asks "Are you sure?", \n in the message is a line break, and wire:confirm.prompt="question|expected" runs the action only when the typed text matches exactly. Without |expected you get Livewire's console warning and nothing runs.
  • The first line of the message is the title and the rest is the text. The dialog uses the confirm settings from the config (warning icon, Yes and Cancel, Cancel focused); wire:confirm.prompt uses the new prompt settings (a text input with OK and Cancel).
  • Works on wire:click and wire:submit, on elements Livewire adds later, and after wire:navigate.
  • Opt out everywhere with 'livewire_confirm' => false in config/sweetalert2.php, or for one element or a whole section with data-swal-native on it or a parent. Both apply only to wire:confirm, not to data-swal-confirm or the promise dialogs.
  • If SweetAlert2 has not loaded, Livewire's own browser confirm() or prompt() is used.
  • Do not put wire:confirm and data-swal-confirm on the same element, or the user is asked twice.
<button wire:click="delete" wire:confirm="Delete this post?\nThis cannot be undone.">Delete</button>

<button wire:click="wipe" wire:confirm.prompt="Type DELETE to wipe the workspace|DELETE">Wipe</button>

{{-- keep the browser's box here --}}
<button wire:click="delete" wire:confirm="Sure?" data-swal-native>Delete</button>

Promise dialogs

Ask a question and await the answer, like confirm() and prompt() but styled. Alpine gets a $swal magic in any x-data; plain JavaScript uses window.LaravelSwal.

  • confirm(message, options) resolves to true when confirmed and false when cancelled or dismissed.
  • prompt(message, defaultValueOrOptions) resolves to the entered text, or null when cancelled. A string second argument is the default value, selected so typing replaces it.
  • alert(message, options) resolves to undefined once the dialog is closed.
  • A string message is split: the first line is the title, the rest is the text. Messages are text, not HTML: titles are shown as text, button labels and footer are escaped and line breaks are kept. Only an explicit html option is inserted as HTML, so never put user input there.
  • confirm() and prompt() use the confirm and prompt settings from the config; alert() uses only the defaults.
  • If SweetAlert2 has not loaded, they fall back to the browser's confirm(), prompt() and alert().
  • TypeScript declarations ship in vendor/amjadiqbal/laravel-sweetalert2/resources/types/laravel-sweetalert2.d.ts.
<button x-data @click="if (await $swal.confirm('Publish now?\nSubscribers get an email.')) $wire.publish()">Publish</button>

<button x-data @click="let name = await $swal.prompt('Rename the project', 'Website'); if (name !== null) $wire.rename(name)">Rename</button>

// Plain JavaScript
if (await LaravelSwal.confirm('Leave without saving?')) {
    history.back();
}

Livewire and Alpine

Use the SweetAlerts trait in a Livewire component to show a popup without a page load. If the action redirects, use the facade instead and the popup shows on the next page.

use AmjadIqbal\SweetAlert2\Livewire\SweetAlerts;

// in the component
$this->swalToast('Profile saved');

<button x-data @click="$dispatch('sweetalert2', { title: 'Hello', icon: 'info' })">Say hello</button>

Security notes

  • title, button labels and footer are escaped.
  • html() and raw() pass values through untouched, so never put user input in them.
  • Options sent from the browser with the sweetalert2 event, fire() or toast() go to SweetAlert2 as they are, so do not put user input in html.
  • With Vite::useCspNonce() every script tag gets the nonce. The SweetAlert2 all build injects its CSS in a <style> tag, so a strict style-src needs 'unsafe-inline' or a Vite build.

Hire me

Need this built into your app, or something custom?

I wrote Laravel SweetAlert2. I can wire it into your Laravel app, extend it for your case, or build the feature around it. Tell me what you need and you'll get a plan and a quote, free.

Support

Found a bug or want a feature? Open an issue on GitHub. For help adding it to your own project, use the quote form above.

More Laravel packages

All packages
Laravel Driver.js: Build Driver.js product tours in PHP and render them with one Blade component.

Laravel Driver.js

Build Driver.js product tours in PHP and render them with one Blade component.

Laravel Sonner: Sonner toast notifications for Laravel, sent from PHP and shown without React.

Laravel Sonner

Sonner toast notifications for Laravel, sent from PHP and shown without React.

Laravel Ninja Keys: A Cmd+K / Ctrl+K command palette for Laravel, with the actions defined in PHP.

Laravel Ninja Keys

A Cmd+K / Ctrl+K command palette for Laravel, with the actions defined in PHP.

Laravel Grid.js: Turn any Eloquent query into a searchable, sortable, paginated Grid.js data table with one fluent PHP call.

Laravel Grid.js

Turn any Eloquent query into a searchable, sortable, paginated Grid.js data table with one fluent PHP call.

Laralink: Work on a Composer package inside the Laravel app that uses it, then switch back to the Packagist release.

Laralink

Work on a Composer package inside the Laravel app that uses it, then switch back to the Packagist release.

Refresher: A drop-in replacement for Laravel's RefreshDatabase that restores a cached snapshot of your test database instead of running migrate:fresh.

Refresher

A drop-in replacement for Laravel's RefreshDatabase that restores a cached snapshot of your test database instead of running migrate:fresh.

Kiln: Artisan commands and an optional signed HTTP route to clear, warm and inspect OPcache when you deploy.

Kiln

Artisan commands and an optional signed HTTP route to clear, warm and inspect OPcache when you deploy.

Laravel Media Viewer: Show private PDFs, video and audio from any Laravel disk without making the files public.

Laravel Media Viewer

Show private PDFs, video and audio from any Laravel disk without making the files public.

Laravel Swiper: Swiper sliders, carousels and image galleries for Laravel as Blade components.

Laravel Swiper

Swiper sliders, carousels and image galleries for Laravel as Blade components.

Laravel MySQL Advisor: Read-only health checks for the MySQL or MariaDB database behind your Laravel app, with the SQL and the Laravel migration to fix a problem wherever a fix applies.

Laravel MySQL Advisor

Read-only health checks for the MySQL or MariaDB database behind your Laravel app, with the SQL and the Laravel migration to fix a problem wherever a fix applies.

Laravel Webhook Console: A dashboard and replay tool for the webhooks spatie/laravel-webhook-client stores in your Laravel app.

Laravel Webhook Console

A dashboard and replay tool for the webhooks spatie/laravel-webhook-client stores in your Laravel app.

Laravel Pennant Dashboard: A browser dashboard for laravel/pennant feature flags: per-scope toggles, sticky percentage rollouts, purge and an audit log.

Laravel Pennant Dashboard

A browser dashboard for laravel/pennant feature flags: per-scope toggles, sticky percentage rollouts, purge and an audit log.

Laravel Notification Inbox: Catches every non-mail Laravel notification in local and staging instead of sending it, and shows each one as it would look on the other end.

Laravel Notification Inbox

Catches every non-mail Laravel notification in local and staging instead of sending it, and shows each one as it would look on the other end.

Laravel WebPush Kit: The browser side of Laravel web push: a subscribe button with a two-step permission prompt, a service worker, and routes that save each user's subscription. Tested in Chrome so far.

Laravel WebPush Kit

The browser side of Laravel web push: a subscribe button with a two-step permission prompt, a service worker, and routes that save each user's subscription. Tested in Chrome so far.

Laravel Redis Advisor: Read-only health checks for the Redis or Valkey behind your Laravel cache, queues, sessions and Horizon, with the redis.conf line or Laravel config that fixes each problem.

Laravel Redis Advisor

Read-only health checks for the Redis or Valkey behind your Laravel cache, queues, sessions and Horizon, with the redis.conf line or Laravel config that fixes each problem.

Laravel First-Party Analytics: Self-hosted web analytics in your Laravel app's own database: visits, sources and UTM campaigns, custom events, conversions and ordered funnels, with no cookies and no stored IP addresses by default.

Laravel First-Party Analytics

Self-hosted web analytics in your Laravel app's own database: visits, sources and UTM campaigns, custom events, conversions and ordered funnels, with no cookies and no stored IP addresses by default.

Laravel Pennant Experiments: A/B and multivariate experiments on laravel/pennant: weighted variants, sticky assignment, exposure and conversion tracking, a z-test and a Bayesian probability to beat control, and a winner rollout.

Laravel Pennant Experiments

A/B and multivariate experiments on laravel/pennant: weighted variants, sticky assignment, exposure and conversion tracking, a z-test and a Bayesian probability to beat control, and a winner rollout.

Laravel SQL Dashboard: Saved SQL queries with typed variables, tables, CSV export, charts, dashboards and scheduled checks that alert by mail, run only on a read-only connection.

Laravel SQL Dashboard

Saved SQL queries with typed variables, tables, CSV export, charts, dashboards and scheduled checks that alert by mail, run only on a read-only connection.

Need something built?

Free quote in 60 seconds