Get Appointment

Blog Single

How to Use SweetAlert2 in Laravel

  • Vfix Technology
  • 24 Dec 2023
  • Laravel
  • 353 Views

Introduction

Laravel is a powerful PHP framework that makes web development easier and more efficient. When it comes to creating user-friendly interfaces, JavaScript libraries like SweetAlert2 can enhance the user experience by providing attractive and customizable pop-up alerts. In this blog post, we will explore how to integrate SweetAlert2 into a Laravel application to create visually appealing and interactive alerts.

What is SweetAlert2?

SweetAlert2 is a JavaScript library that allows you to replace your browser's default alert and confirmation dialogs with custom, beautifully designed modals. It's highly customizable and can be integrated into various web development frameworks, including Laravel.

Prerequisites

Before we dive into integrating SweetAlert2 in Laravel, make sure you have the following prerequisites in place:

  1. A Laravel application set up on your local environment or a web server.

  2. Composer installed on your system.

  3. Basic knowledge of Laravel and JavaScript.

Integrating SweetAlert2 into Laravel

Follow these steps to integrate SweetAlert2 into your Laravel application:

Step 1: Install the laravel

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

Step 2: Now you can use the cdn for the sweet alert 2 or can download the css or js

add path to your css in the head.

<link rel="stylesheet" href="{{ asset('css/sweet-alert2.css') }}">

now add the js link in the footer

<script src="{{ asset('js/sweet-alert2.min.js') }}"></script>

after this add the js code below it. 

$(document).ready(function() {
    // show error message
    @if($errors - > any())
    //var errorMessage = @json($errors->any()); // Get the first validation error message
    var Toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 5500
    });

    Toast.fire({
        icon: 'error',
        title: 'There are form validation errors. Please fix them.'
    });
    @endif

    // success message
    @if(session('success'))
    var successMessage = @json(session('success')); // Get the first sucess message
    var Toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 5500
    });

    Toast.fire({
        icon: 'success',
        title: successMessage
    });
    @endif

});

Here when there will be success message the js will through the success message and on error it will through the error message

Share :


+91 8447 525 204 Request Estimate