How to Install Sweetalert2 in Laravel ?

 

To install SweetAlert2 CDN along with jQuery in a Laravel project, follow these steps:


1. Create a New Laravel Project (if not already done):


If you haven't set up a Laravel project yet, you can do so using Composer. Open your terminal and run the following commands:


composer create-project --prefer-dist laravel/laravel YourProjectName

cd YourProjectName


2. Include jQuery and SweetAlert2 CDN in Your Layout File:


Open your layout file (e.g., `resources/views/layouts/app.blade.php`) and add the following code to include jQuery and SweetAlert2 CSS and JavaScript from the CDNs:


<!DOCTYPE html>

<html lang="en">

<head>

    <!-- ... other head elements ... -->


    <!-- Include jQuery from the CDN -->

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


    <!-- Include SweetAlert2 CSS from the CDN -->

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18/dist/sweetalert2.min.css">


    <!-- ... more head elements ... -->

</head>

<body>

    <!-- ... body content ... -->


    <!-- Include SweetAlert2 JavaScript from the CDN -->

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18/dist/sweetalert2.all.min.js"></script>

    

    <!-- ... more body content ... -->

</body>

</html>


This code snippet includes jQuery and SweetAlert2 CSS and JavaScript files from the CDNs. Place the code within the appropriate sections of your layout file.


3. Use SweetAlert2 with jQuery in Your Laravel Views:


Now that jQuery and SweetAlert2 are included via the CDNs, you can use them in your Laravel views. Here's an example of how to use SweetAlert2 along with jQuery to display a simple alert:


In your view file (e.g., `resources/views/welcome.blade.php`), add a button that triggers the SweetAlert2 alert:


<button id="show-alert">Show SweetAlert2 Alert</button>


<script>

$(document).ready(function() {

    $('#show-alert').click(function() {

        Swal.fire('Hello!', 'This is a SweetAlert2 alert!', 'success');

    });

});

</script>


Make sure to include the jQuery and SweetAlert2 JavaScript files in your layout file (e.g., `resources/views/layouts/app.blade.php`) so that they're available across all your views:


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script src="{{ asset('js/app.js') }}" defer></script>



Example Output:



That's it! You've successfully installed and integrated SweetAlert2 and jQuery into your Laravel project using the CDNs. You can now use SweetAlert2 along with jQuery to create customized alerts and modals in your application.