How To Use Sweetalert2 In Laravel

Websolutionstuff | May-03-2021 | Categories : Laravel PHP jQuery

Today we will learn how to use sweetalert2 In laravel, You can use sweetalert2 in laravel as well as php, sweetalert2 is used for create differents type of custom alert messages or you can create custom popups like success messages, error messages, warning modals, confirm modals, custom notifications etc..

Normally, javascript provide simple alert box in your browser but if you want to dispaly custom popup then sweetalert2 is very effective library which allows us to create all kinds of alert messages that can be customized to match the look and feel of our own website.

So let's start and see how to implement sweetalert2 In laravel.

Step 1 : Download or Install Using CDN 

 We need to add js file css file in our to implement sweetalert2 in laravel.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.all.min.js"></script>
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.min.css'>

 

Step 2 : Call the sweetAlert2

Now, we need to call the sweetAlert2 function after the page has loaded.

Here, i am giving you simple example.

Swal.fire(
  'Websolutionstuff!',
  'Button Clicked',
  'success'
)

 

Output : 

sweetalert2

 

 

Here we will see different type of sweetalert2 example.

Example 1 : Simple message 

 

Swal.fire('Hello')

 

Example 2 : Title with text

 

Swal.fire(
  'The Demo?',
  'This is Demo ?',
  'Asking'
)

 

Example 3 :  Modal with title, icon, text and footer

 

Swal.fire({
  icon: 'error',
  title: 'Not Found...',
  text: 'Something went wrong!',
  footer: '<a href>Are you facing any issue?</a>'
})

 

Example 4 :  Modal window with a long content

 

Swal.fire({
  imageUrl: 'https://placeholder.pics/svg/300x1500',
  imageHeight: 1500,
  imageAlt: 'Big image'
})

 

Example 5 : Custom HTML description and buttons with ARIA labels

 

Swal.fire({
  title: '<strong>HTML <u>example</u></strong>',
  icon: 'info',
  html:
    'You can use <b>bold text</b>, ' +
    '<a href="//sweetalert2.github.io">links</a> ' +
    'and other HTML tags',
  showCloseButton: true,
  showCancelButton: true,
  focusConfirm: false,
  confirmButtonText:
    '<i class="fa fa-thumbs-up"></i> Great!',
  confirmButtonAriaLabel: 'Thumbs up, great!',
  cancelButtonText:
    '<i class="fa fa-thumbs-down"></i>',
  cancelButtonAriaLabel: 'Thumbs down'
})

 

 

Example 6 : Dialog with three buttons

 

Swal.fire({
  title: 'Do you want to save the changes?',
  showDenyButton: true,
  showCancelButton: true,
  confirmButtonText: `Save`,
  denyButtonText: `Don't save`,
}).then((result) => {
  /* Read more about isConfirmed, isDenied below */
  if (result.isConfirmed) {
    Swal.fire('Saved!', '', 'success')
  } else if (result.isDenied) {
    Swal.fire('Changes are not saved', '', 'info')
  }
})

 

Example 7 : Custom positioned

 

Swal.fire({
  position: 'top-end',
  icon: 'success',
  title: 'Your work has been saved',
  showConfirmButton: false,
  timer: 1500
})

 

Example 8 : Confirm dialog box with a confirm button

 

Swal.fire({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  icon: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!'
}).then((result) => {
  if (result.isConfirmed) {
    Swal.fire(
      'Deleted!',
      'Your file has been deleted.',
      'success'
    )
  }
})

 

Example 9 : Modal with a custom image

 

Swal.fire({
  title: 'Sweet!',
  text: 'Modal with a custom image.',
  imageUrl: 'https://unsplash.it/400/200',
  imageWidth: 400,
  imageHeight: 200,
  imageAlt: 'Custom image',
})

 

Example 10 : Model with autoclose timer
let timerInterval
Swal.fire({
  title: 'Auto close alert!',
  html: 'I will close in <b></b> milliseconds.',
  timer: 2000,
  timerProgressBar: true,
  didOpen: () => {
    Swal.showLoading()
    timerInterval = setInterval(() => {
      const content = Swal.getContent()
      if (content) {
        const b = content.querySelector('b')
        if (b) {
          b.textContent = Swal.getTimerLeft()
        }
      }
    }, 100)
  },
  willClose: () => {
    clearInterval(timerInterval)
  }
}).then((result) => {
  /* Read more about handling dismissals below */
  if (result.dismiss === Swal.DismissReason.timer) {
    console.log('I was closed by the timer')
  }
})

 

Example 11: AJAX request example
Swal.fire({
  title: 'Submit your Github username',
  input: 'text',
  inputAttributes: {
    autocapitalize: 'off'
  },
  showCancelButton: true,
  confirmButtonText: 'Look up',
  showLoaderOnConfirm: true,
  preConfirm: (login) => {
    return fetch(`//api.github.com/users/${login}`)
      .then(response => {
        if (!response.ok) {
          throw new Error(response.statusText)
        }
        return response.json()
      })
      .catch(error => {
        Swal.showValidationMessage(
          `Request failed: ${error}`
        )
      })
  },
  allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
  if (result.isConfirmed) {
    Swal.fire({
      title: `${result.value.login}'s avatar`,
      imageUrl: result.value.avatar_url
    })
  }
})

 

Recommended Post
Featured Post
Laravel 10 Scout Search and Algolia Example
Laravel 10 Scout Search and Al...

Hey everyone! Ever wished your Laravel application could deliver lightning-fast search results? Well, I've got great...

Read More

Feb-21-2024

How To Validate Password And Confirm Password In React JS
How To Validate Password And C...

In this article, we will see how to validate password and confirm password in react js. Sometimes we need to add th...

Read More

Sep-14-2022

7 Easy Steps: Create Laravel 10 Livewire CRUD Operation
7 Easy Steps: Create Laravel 1...

Hey there! I'm diving into the world of Laravel 10 and Livewire, and I'm excited to share a step-by-step guide o...

Read More

Dec-06-2023

Laravel 10: New Features And Release Date
Laravel 10: New Features And R...

In our ever-changing digital landscape, staying ahead of the competition is essential. And that's precisely what we&...

Read More

Jan-11-2023