In web development, user interaction plays a critical role in shaping user experience. When it comes to confirming deletions, providing a clear and visually appealing prompt is crucial. Laravel 11, a robust PHP framework, combined with SweetAlert2, an elegant and feature-rich JavaScript library, makes this task seamless.
In this blog, we'll delve into how you can integrate SweetAlert2 in Laravel 11 to handle confirmation prompts for deletions. Not only will we simplify the process, but we'll also show you why this combination is a game-changer for developers and businesses alike.
SweetAlert2 is an upgraded, more customizable version of the original SweetAlert library. It provides developers with a clean, modern design for alerts, confirmation boxes, and even custom modals. Unlike default browser alerts, SweetAlert2 lets you:
For small businesses, using such tools ensures that their web apps are not just functional but also visually appealing.
Before we dive into coding, you’ll need to set up your Laravel 11 project with SweetAlert2. Here's a step-by-step guide:
If you’re starting from scratch, run:
composer create-project <a href="/blog/in-laravel-how-to-use-partial-template">laravel</a>/<a href="/blog/best-laravel-packages-to-build-powerful-crm-applications">laravel</a> <a href="/blog/using-faker-in-laravel-to-generate-random-dates">laravel</a>-sweetalert
This will set up a clean Laravel 11 environment.
Laravel supports Node.js packages, so installing SweetAlert2 is straightforward:
npm install sweetalert2
Once installed, make sure to compile the assets by running:
npm run dev
After installation, you need to import SweetAlert2 into your application. Open resources/js/app.js
and add:
import Swal from "sweetalert2";
window.Swal = Swal;
Finally, compile your changes:
npm run dev
To demonstrate SweetAlert2 in Laravel 11, let’s create a basic example for deleting a record.
In routes/web.php
, add:
use App\Http\Controllers\ItemController;
Route::get('/items', [ItemController::class, 'index']);
Route::delete('/items/{id}', [ItemController::class, 'destroy'])->name('items.destroy');
Run the Artisan command to generate a controller:
php artisan make:controller ItemController
In ItemController.php
, add methods to display and delete items:
public function index()
{
$items = Item::all();
return view('items.index', compact('items'));
}
public function destroy($id)
{
$item = Item::findOrFail($id);
$item->delete();
return response()->json(['success' => 'Item deleted successfully!']);
}
Now that the backend is ready, let’s create the frontend to implement SweetAlert2 for deletion confirmation.
In resources/views/items/index.blade.php
, create the following structure:
@extends('layouts.app') @section('content')
<div class="container">
<h1>Items List</h1>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach($items as $item)
<tr>
<td>{{ $item->id }}</td>
<td>{{ $item->name }}</td>
<td>
<button class="btn btn-danger btn-delete" data-id="{{ $item->id }}">
Delete
</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
In the same Blade file, add a script section for handling the delete confirmation:
<script>
document.querySelectorAll('.btn-delete').forEach(button => {
button.addEventListener('click', function () {
const id = this.dataset.id;
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.value) {
fetch(`/items/${id}`, {
method: 'DELETE',
headers: {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
}
}).then(response => response.json())
.then(data => {
if (data.success) {
Swal.fire('Deleted!', data.success, 'success');
location.reload();
}
});
}
});
});
});
</script>
Visual Appeal: Default browser alerts are dull. SweetAlert2 provides elegant, modern designs that align with your site's branding.
Improved Usability: Features like custom buttons, animations, and icons make your app more intuitive.
Asynchronous Support: The ability to work with promises makes SweetAlert2 perfect for AJAX-based Laravel apps.
At Prateeksha Web Design, we specialize in creating modern web applications that balance functionality with aesthetic appeal. Our expertise in Laravel ensures that small businesses can leverage the latest technologies like SweetAlert2 to enhance their digital platforms.
If you’re looking for a team to build your next project or optimize an existing one, Prateeksha Web Design is here to help.
Using SweetAlert2 in Laravel 11 for confirming deletions not only makes your app more user-friendly but also adds a layer of professionalism to its design. From the value of result.value to the elegance of delete prompts, this guide has covered everything you need to get started.
Reach out to Prateeksha Web Design to see how we can transform your ideas into impactful solutions. With our help, even complex tasks like deletion confirmation can become opportunities to delight your users.
Prateeksha Web Design offers comprehensive services to teach clients how to use SweetAlert2 in Laravel 11 for confirming deletions. This includes detailed guidance on integrating SweetAlert2 into Laravel, setting up the confirmation mechanism, as well as testing and troubleshooting. The service also includes on-demand support and code review to ensure smooth implementation.
Interested in learning more? Contact us today.