Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Oscar165's avatar

sweetalert2 getting it to work

https://github.com/limonte/sweetalert2 Installed using npm but I am lost on what to do after that.

Added the scripts and css to public.

This is the call swal('Hello world!')

Any help would be awesome...

0 likes
11 replies
andersfloor's avatar

It depends on what you want to to. Do you have problems getting the sweetalert popup to show, or are you looking to easily integrate it in your controllers? If that's what you want, there's a Laravel package that makes that part quite easy: https://github.com/Infinety/alerts

If you install it according to the instructions, it should work fine. Please note that it comes with the sweetalert js and css file, which will be put into the public folder when you execute the php artisan vendor:publish --tag=alerts command, so that might overwrite the files you already put into the public folder.

1 like
Oscar165's avatar

Thanks for your answer, the question is about the sweetalert2 package that is sweeter then sweet alerts. Its does not have and install for laravel. Its is a javascript fileand css.

My questions was how would that be integrated into laravel?

Can java-script libraries be called from anywhere in laravel?

andersfloor's avatar

Javascript-libraries and Laravel are kind of two separate worlds. Laravel works server-side, javascript works client-side. With Laravel you create views (blade), and in those views you can call all the javascript and html that you want.

Imagine you start with a new project. Install the Infinety/alerts-package with the instructions as mentioned on their page.

Use this for example in your routes file (or in a controller):

Route::get('/', function () {
    // Simply shows the blade view resources/home.blade.php
    return view('home');
});

Route::post('/justapage', function() {

    // This is the message that will show in the sweetalert-popup:
    alert()->success('It worked!', 'The form was submitted');

    // Redirect back to the page you were looking at
    return back();
});

And use this as resources/home.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>

    <title>Demo</title>
    <!-- include sweetalert2 css library -->
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/sweetalert2/5.3.5/sweetalert2.min.css">

</head>
<body>
    <H1>Homepage</h1>

    <form action="/justapage" method="post">
        {{ csrf_field() }}
        <button type="submit">Click me!</button>
    </form>

    <!-- include sweetalert2 js library. Note: place it in the body, not in the head -->
    <script src="https://cdn.jsdelivr.net/sweetalert2/5.3.5/sweetalert2.min.js"></script>

    <!-- And is where Laravel and javascript come together -->
    <!-- This include basically writes the neccessary javascript: -->
    @include('Alerts::alerts')

</body>
</html>

(I used the sweetalert2-CDN-files here)

When you click the button, it should show the sweetalert2 popup Sweetalert2 popup

If you check out the source of the webpage, you will see that the @include('Alerts::alert')-line has outputted this javascript:

    <script>
        swal({
            title: "It worked!",
            text:  "The form was submitted",
            type: "success",
            timer: 2500,
            showConfirmButton: false
        });
    </script>

Instead of this:

alert()->success('Title', 'Message');

you can also use:

alert()->overlay('Title', 'Message', 'success');

-> this will add a close button to the sweetalert popup and prevent it from closing automatically.

2 likes
andersfloor's avatar

Btw, I use sweetalert2 a lot in my current project. I especially love the interactive possibilities combined with Ajax requests and chained sweetalert commands. It took me hours to figure this out and there's not much documentation to be found on this part, so let me share that here as well:

sweetalert2 popup with form field

Blade view:

    <a class="btn btn-lg btn-primary" id="addfriend" role="button">Add as friend</a>
var sa_title;
var sa_type;
var sa_msg;
var friendname = '{{$user->username}}'; // e.g. 'Eric'
var friendtitle = '{{ $user->HeShe ) }}'; // e.g. 'He' or 'She'

$(document).ready(function() {

    $('#addfriend').click(function() {
        swal({
            title: 'Friendship request',
            text: 'You wish to send ' + friendname + ' a friendship request. If you want you can add a personal note.',
            type: 'info',
            input: 'textarea',
            confirmButtonText: 'Send request',
            showCancelButton: true,
            showLoaderOnConfirm: true,
            inputValidator: function(textarea) {
                return new Promise(function(resolve, reject) {
                    if (textarea.length>200) {
                        reject('Your text is too long. Please use no more than 200 characters.');
                    } else {
                        resolve();
                    }
                });
            },
            preConfirm: function(textarea) {
                return new Promise(function(resolve, reject) {

                    // Make jQuery Ajax-request
                    $.ajax({
                        data       : 'msg=' + textarea,
                        cache      : false,
                        processData: false,
                        dataType   : 'json',
                        method     : 'POST',
                        url        : '/async/addfriend/' + friendname,
                        success: function() {
                            // Set content for success-sweetalert
                            sa_title = 'Success!';
                            sa_msg = friendname + ' has received your request.';
                            sa_msg += friendtitle + ' needs to accept it first though.'
                            sa_type = 'success';
                            resolve();
                        },
                        error: function(response) {
                            // Set content for failure-sweetalert
                            sa_title = 'Oops!';
                            sa_msg = 'Something went wrong. Please try again or contact us.';
                            sa_type = 'error';
                            reject('We were unable to process your request');
                        }
                    });
                });
            },
            allowOutsideClick: false
        }).then(function() {
            swal({
                // Show success or failure sweetalert
                title: sa_title,
                html: sa_msg + "",
                type: sa_type
            }).then(function() {
                // Hide button
                $('#addfriend').hide('slow');
//          }).done(); // Deprecated, see comment by limonte below
            }).catch(swal.noop());
//      }).done(); // Deprecated, see comment by limonte below
        }).catch(swal.noop());

    });
});

In this case, I make a post request to the url /async/addfriend/Eric - which should return a valid response or an error.

2 likes
yansusanto's avatar

@limonte @andersfloor

alert('Title', 'Message')
alert()->error('Title', 'Message')
alert()->success('Title', 'Message')
alert()->overlay('Title', 'Message')

Do we only have the above options to use on our controller?

What if I want to use this on my controller? How do we set the position: 'top-end' and show the showCloseButton: true?

swal({
  position: 'top-end',
  type: 'success',
  title: 'Your work has been saved',
  showCloseButton: true,
  timer: 1500
})
nouvre's avatar

And like a lot of the code posted a year or more ago, this appears to no longer work, as demonstrated above. The package highlighted above is 2-3 years old, which is problematic usually. And following these steps, I get no alert. In source, @include('Alerts::alert') has outputted .... nothing.

dru's avatar

I think you are missing some stuff, like the javascript that activates sweetalert like so:

swal({ "timer":1800, "title":"Título", "text":"Notificación Básica", "showConfirmButton":false });

it would depend on the version, but googling I found this in spanish

https://rimorsoft.com/sweetalert-en-laravel-5-5

I hope this somehow helps

Please or to participate in this conversation.