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.
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.
Before we dive into integrating SweetAlert2 in Laravel, make sure you have the following prerequisites in place:
A Laravel application set up on your local environment or a web server.
Composer installed on your system.
Basic knowledge of Laravel and JavaScript.
Follow these steps to integrate SweetAlert2 into your Laravel application:
composer create-project --prefer-dist laravel/laravel project-name
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