PHPackages                             sweetalert2/laravel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. sweetalert2/laravel

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

sweetalert2/laravel
===================

Official SweetAlert2 integration for Laravel framework

1.4.1(2mo ago)3820.9k↓10.8%3MITPHPCI passing

Since Apr 21Pushed 2mo ago2 watchersCompare

[ Source](https://github.com/sweetalert2/sweetalert2-laravel)[ Packagist](https://packagist.org/packages/sweetalert2/laravel)[ RSS](/packages/sweetalert2-laravel/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (39)Used By (0)

Official SweetAlert2 integration for Laravel framework
======================================================

[](#official-sweetalert2-integration-for-laravel-framework)

### Demos: [Inertia + React](https://github.com/sweetalert2/sweetalert2-laravel-inertia-react-demo/) | [Livewire](https://github.com/sweetalert2/sweetalert2-laravel-livewire-demo)

[](#demos-inertia--react--livewire)

Installation
============

[](#installation)

```
composer require sweetalert2/laravel
```

Include the SweetAlert2 template in your layout file (usually `resources/views/layouts/app.blade.php`):

```
@include('sweetalert2::index')
```

Usage
=====

[](#usage)

Laravel Controllers, Middleware, Views etc.
-------------------------------------------

[](#laravel-controllers-middleware-views-etc)

You can now call `Swal::fire()` or any of the available helper methods anywhere in your Laravel application (controllers, middleware, etc.) to show a SweetAlert2 alert:

```
use SweetAlert2\Laravel\Swal;

// same as `Swal.fire()` in JS, same options: https://sweetalert2.github.io/#configuration
Swal::fire([
    'title' => 'Laravel + SweetAlert2 =  {
        toast.onmouseenter = Swal.stopTimer;
        toast.onmouseleave = Swal.resumeTimer;
    }',
]);
```

For more details on using callbacks, see [FAQ #4](#4-what-are-the-limitations).

[![SweetAlert2 Laravel](sweetalert2-laravel.png)](sweetalert2-laravel.png)

Livewire Components
-------------------

[](#livewire-components)

You can now call `$this->swalFire` or any of the available helper methods in your Livewire component to show realtime popups and toasts:

#### LivewireExample.php

[](#livewireexamplephp)

```
use Livewire\Component;
use SweetAlert2\Laravel\Traits\WithSweetAlert;

class LivewireExample extends Component
{
    use WithSweetAlert;

    public function save(): void
    {
        // same as `Swal.fire()` in JS, same options: https://sweetalert2.github.io/#configuration
        $this->swalFire([
            'title' => 'Saved successfully!',
            'text' => 'The save method was called successfully!',
            'icon' => 'success',
            'confirmButtonText' => 'Lovely'
        ]);
    }
}
```

The full list of options can be found in the [SweetAlert2 documentation](https://sweetalert2.github.io/#configuration).

#### livewire-example.blade.php

[](#livewire-examplebladephp)

```

  Save

```

### Helpers

[](#helpers-1)

Available Livewire helper methods:

```
// with a custom icon
$this->swalSuccess([
    'title' => 'Popup with a success icon',
]);
$this->swalError([
    'title' => 'Popup with an error icon',
]);
$this->swalWarning([
    'title' => 'Popup with a warning icon',
]);
$this->swalInfo([
    'title' => 'Popup with an info icon',
]);
$this->swalQuestion([
    'title' => 'Popup with a question icon',
]);

// or a toast
$this->swalToast([
    'title' => 'Toast',
]);

// or a toast with a custom icon
$this->swalToastSuccess([
    'title' => 'Toast with a success icon',
]);
$this->swalToastError([
    'title' => 'Toast with an error icon',
]);
$this->swalToastWarning([
    'title' => 'Toast with a warning icon',
]);
$this->swalToastInfo([
    'title' => 'Toast with an info icon',
]);
$this->swalToastQuestion([
    'title' => 'Toast with a question icon',
]);
```

### Using JavaScript Callbacks in Livewire

[](#using-javascript-callbacks-in-livewire)

Just like in Laravel controllers, you can use JavaScript callbacks in Livewire components:

```
$this->swalFire([
    'title' => 'Processing...',
    'toast' => true,
    'position' => 'top-end',
    'icon' => 'info',
    'timer' => 3000,
    'timerProgressBar' => true,
    'didOpen' => '(toast) => {
        toast.onmouseenter = Swal.stopTimer;
        toast.onmouseleave = Swal.resumeTimer;
    }',
]);
```

Inertia.js
----------

[](#inertiajs)

You can use `Swal::fire()` or any of the available helper methods in your Inertia.js controllers to show popups after navigation:

### Setup

[](#setup)

First, add the SweetAlert2 flash data to your `HandleInertiaRequests` middleware:

```
use SweetAlert2\Laravel\Swal;

public function share(Request $request): array
{
    return array_merge(parent::share($request), [
        'flash' => [
            Swal::SESSION_KEY => fn () => $request->session()->pull(Swal::SESSION_KEY),
        ],
    ]);
}
```

Then include the SweetAlert2 template in your Inertia app layout (usually `resources/views/app.blade.php` or similar):

```
@include('sweetalert2::index')
```

### Usage

[](#usage-1)

#### InertiaController.php

[](#inertiacontrollerphp)

```
use SweetAlert2\Laravel\Swal;
use Inertia\Inertia;

class InertiaController extends Controller
{
    public function store()
    {
        // Your logic here...

        // Show SweetAlert2 popup after redirect
        Swal::success([
            'title' => 'Saved!',
            'text' => 'Your data has been saved successfully.',
        ]);

        return redirect()->route('dashboard');
    }
}
```

The full list of options can be found in the [SweetAlert2 documentation](https://sweetalert2.github.io/#configuration).

### Helpers

[](#helpers-2)

Available Inertia helper methods (same as Laravel helpers):

```
// with a custom icon
Swal::success([
    'title' => 'Popup with a success icon',
]);
Swal::error([
    'title' => 'Popup with an error icon',
]);
Swal::warning([
    'title' => 'Popup with a warning icon',
]);
Swal::info([
    'title' => 'Popup with an info icon',
]);
Swal::question([
    'title' => 'Popup with a question icon',
]);

// or a toast
Swal::toast([
    'title' => 'Toast',
]);

// or a toast with a custom icon
Swal::toastSuccess([
    'title' => 'Toast with a success icon',
]);
Swal::toastError([
    'title' => 'Toast with an error icon',
]);
Swal::toastWarning([
    'title' => 'Toast with a warning icon',
]);
Swal::toastInfo([
    'title' => 'Toast with an info icon',
]);
Swal::toastQuestion([
    'title' => 'Toast with a question icon',
]);
```

FAQ
===

[](#faq)

1. How is this different to the [realrashid/sweet-alert](https://github.com/realrashid/sweet-alert) package?
------------------------------------------------------------------------------------------------------------

[](#1-how-is-this-different-to-the-realrashidsweet-alert-package)

The `realrashid/sweet-alert` package is too opinionated and too complex: facade, midddleware, adding vendor files, whatnot 🤯. And all that with 0 tests.

This package is simple, straightforward, and unopinionated. Its API is aimed to be as close as possible to the original [sweetalert2](https://sweetalert2.github.io/#configuration).

It simply provides a way to use SweetAlert2 in your Laravel, Livewire, or Inertia.js application without touching JS or CSS files.

2. How does it work?
--------------------

[](#2-how-does-it-work)

Depending on whether you use the Swal class or the WithSweetAlert trait, within either a Laravel only, Livewire, or Inertia.js context, the behaviour is slightly different.

### Laravel controllers, middleware, views etc

[](#laravel-controllers-middleware-views-etc-1)

1. The `Swal::fire()` method will pass the options to the session using `session()->put()`.
2. The blade partial template will check if there is any session data and will render the SweetAlert2 popup, removing the data with `session()->pull()` after displaying it.

### Livewire components

[](#livewire-components-1)

#### Realtime

[](#realtime)

1. The `$this->swalFire()` method will dispatch a [Livewire event](https://livewire.laravel.com/docs/events) with the options to the browser window within the current request.
2. The blade partial template will listen for the Livewire event and will render the SweetAlert2 popup.

This works on the first request and subsequent Livewire update requests.

#### First request or after redirect

[](#first-request-or-after-redirect)

1. The `Swal::fire()` method will pass the options to the session using `session()->put()`.
2. The blade partial template will show a popup on the initial page render, removing the data with `session()->pull()` after displaying it.

This works across multiple requests (including lazy-loaded components) until the alert is displayed.

This is ideal for showing messages after redirecting the user from a Livewire component, for example if they lack permissions to view a page:

```
public function boot()
{
    if (Gate::denies('viewAny', Appointments::class)) {
        Swal::error([
            'title' => 'Unauthorized',
            'text' => 'You aren\'t authorized to view appointments!',
            'confirmButtonText' => 'Close'
        ]);
        return redirect()->route('index');
    }
}
```

### Inertia.js

[](#inertiajs-1)

1. The `Swal::fire()` method will pass the options to the session using `session()->put()`.
2. The `HandleInertiaRequests` middleware shares the session data with Inertia via shared props, removing it with `session()->pull()`.
3. The blade partial template listens for Inertia navigation events and renders the SweetAlert2 popup.

This works after Inertia page navigations (redirects, visits, etc.).

3. How is the SweetAlert2 JavaScript library loaded?
----------------------------------------------------

[](#3-how-is-the-sweetalert2-javascript-library-loaded)

This package uses a smart loading strategy for the SweetAlert2 library:

1. **Check for existing SweetAlert2**: If `window.Swal` is already available, it will use the existing import.
2. **Dynamic CDN loading**: If SweetAlert2 is not loaded, it will dynamically import it from the official CDN (`https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.esm.all.min.js`).

4. What are the limitations?
----------------------------

[](#4-what-are-the-limitations)

SweetAlert2 is a JavaScript package and some of its options are JS callbacks. While you can pass JavaScript callback functions as strings in the `Swal::fire()` or `$this->swalFire()` methods, keep in mind:

1. **Callbacks must be passed as strings**: Write your JavaScript function as a string. For example:

```
Swal::fire([
    'title' => 'Toast notification',
    'toast' => true,
    'position' => 'top-end',
    'didOpen' => '(toast) => { toast.onmouseenter = Swal.stopTimer; toast.onmouseleave = Swal.resumeTimer; }',
]);
```

2. **Supported callback options**: The following callback options are supported and will be rendered as JavaScript functions:

    - `didOpen`
    - `didClose`
    - `didDestroy`
    - `willOpen`
    - `willClose`
    - `didRender`
    - `preDeny`
    - `preConfirm`
    - `inputValidator`
    - `inputOptions`
3. **Callback limitations**:

    - You cannot use PHP variables directly in callback strings (use JavaScript variables or values from the alert instead)
    - Complex logic should be kept in JavaScript files and called from the callbacks
    - For advanced use cases, consider using the SweetAlert2 API directly in JavaScript
4. **Security considerations**:

    - Callback strings are executed as JavaScript in the browser
    - **⚠️ CRITICAL: Only pass callback strings from trusted sources (your PHP backend code)**
    - **⚠️ NEVER pass user input directly as callback strings** to prevent XSS (Cross-Site Scripting) vulnerabilities
    - The package includes built-in XSS protection that escapes dangerous patterns in callbacks, but this is a defense-in-depth measure
    - Always validate and sanitize user input before including it in any SweetAlert2 options
    - If you need to include dynamic user-provided data, use regular options (like `title`, `text`, `html`) which are safely JSON-encoded
    - Example of unsafe usage (NEVER do this): ```
        // ❌ UNSAFE - DO NOT DO THIS
        Swal::fire([
            'didOpen' => $_GET['callback'], // User input as callback = XSS vulnerability!
        ]);
        ```
    - Example of safe usage: ```
        // ✅ SAFE - User data in regular options, callbacks from your code
        Swal::fire([
            'title' => htmlspecialchars($_GET['message']), // User input safely encoded
            'didOpen' => '(popup) => { console.log("Opened"); }', // Your trusted code
        ]);
        ```

### Example: Toast with Timer Control

[](#example-toast-with-timer-control)

```
use SweetAlert2\Laravel\Swal;

Swal::fire([
    'title' => 'Your session will expire soon',
    'toast' => true,
    'position' => 'top-end',
    'icon' => 'warning',
    'showConfirmButton' => false,
    'timer' => 3000,
    'timerProgressBar' => true,
    'didOpen' => '(toast) => {
        toast.onmouseenter = Swal.stopTimer;
        toast.onmouseleave = Swal.resumeTimer;
    }',
]);
```

###  Health Score

51

—

FairBetter than 96% of packages

Maintenance88

Actively maintained with recent releases

Popularity39

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 83.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~12 days

Total

28

Last Release

61d ago

Major Versions

0.2.0 → 1.0.02025-08-24

### Community

Maintainers

![](https://www.gravatar.com/avatar/1973411272db2d2a0561f3832781a1691b44677ca2b1dcd945b567776e6f0259?d=identicon)[sweetalert2](/maintainers/sweetalert2)

---

Top Contributors

[![limonte](https://avatars.githubusercontent.com/u/6059356?v=4)](https://github.com/limonte "limonte (46 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (6 commits)")[![SlothLady](https://avatars.githubusercontent.com/u/95983565?v=4)](https://github.com/SlothLady "SlothLady (2 commits)")[![renovate[bot]](https://avatars.githubusercontent.com/in/2740?v=4)](https://github.com/renovate[bot] "renovate[bot] (1 commits)")

---

Tags

laravelsweetalert2

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/sweetalert2-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/sweetalert2-laravel/health.svg)](https://phpackages.com/packages/sweetalert2-laravel)
```

###  Alternatives

[wireui/wireui

TallStack components

1.8k1.3M16](/packages/wireui-wireui)[livewire/volt

An elegantly crafted functional API for Laravel Livewire.

4205.3M84](/packages/livewire-volt)[ramonrietdijk/livewire-tables

Dynamic tables for models with Laravel Livewire

21147.4k](/packages/ramonrietdijk-livewire-tables)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
