Implementing Sweet Alert Delete Confirmation in Laravel 8: A Step-by-Step Guide

Implementing Sweet Alert Delete Confirmation in Laravel 8: A Step-by-Step Guide

Sweet Alert is a popular JavaScript library for creating beautiful and customizable alert boxes. In Laravel 8, integrating Sweet Alert for delete confirmations enhances user experience by providing a visually appealing and interactive way to confirm actions.

Overview of Using Sweet Alert for Delete Confirmation in Laravel 8

  1. Install Sweet Alert: Add Sweet Alert to your project using a CDN or by installing it via npm.
  2. Create a Delete Button: In your Blade template, create a delete button and attach a click event listener.
  3. Trigger Sweet Alert: Use the Swal.fire method to display a confirmation dialog when the delete button is clicked.
  4. Handle User Response: If the user confirms, proceed with the deletion using an AJAX request or form submission.

Importance and Benefits

  • User-Friendly: Provides a clear and attractive way to confirm actions, reducing accidental deletions.
  • Customizable: Easily customize the alert’s appearance and behavior to match your application’s design.
  • Interactive: Enhances user interaction by making confirmations more engaging and less intrusive.

Implementing Sweet Alert for delete confirmations in Laravel 8 not only improves the user interface but also ensures a smoother and more secure user experience.

Step 1: Install Laravel 8

Here’s a step-by-step guide to install Laravel 8 and set up Sweet Alert for delete confirmation:

  1. Install Laravel 8:

    composer create-project --prefer-dist laravel/laravel laravel8app
    cd laravel8app
    

  2. Set Up Database:

    • Configure your .env file with your database credentials.
    • Run migrations:
      php artisan migrate
      

  3. Install Sweet Alert Package:

    composer require realrashid/sweet-alert
    

  4. Configure Sweet Alert:

    • Add the service provider in config/app.php:
      'providers' => [
          RealRashid\SweetAlert\SweetAlertServiceProvider::class,
      ],
      

    • Add the alias:
      'aliases' => [
          'Alert' => RealRashid\SweetAlert\Facades\Alert::class,
      ],
      

    • Publish the package assets:
      php artisan vendor:publish --provider="RealRashid\SweetAlert\SweetAlertServiceProvider"
      

  5. Include Sweet Alert in Your Layout:

    • Add the following in your main layout file (e.g., resources/views/layouts/app.blade.php):
      @include('sweetalert::alert')
      

  6. Create Routes and Controller:

    • Define routes in routes/web.php:
      Route::resource('users', UserController::class);
      

    • Create a controller:
      php artisan make:controller UserController
      

  7. Implement Delete Functionality:

    • In UserController, add the delete method:
      public function destroy($id)
      {
          User::find($id)->delete();
          return redirect()->route('users.index')->with('success', 'User deleted successfully.');
      }
      

  8. Add Sweet Alert to Your Blade View:

    • In your view file (e.g., resources/views/users/index.blade.php), add the delete button with Sweet Alert:
      <form action="{{ route('users.destroy', $user->id) }}" method="POST" id="delete-form-{{ $user->id }}">
          @csrf
          @method('DELETE')
          <button type="button" onclick="confirmDelete({{ $user->id }})">Delete</button>
      </form>
      
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
      <script>
          function confirmDelete(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.isConfirmed) {
                      document.getElementById('delete-form-' + id).submit();
                  }
              })
          }
      </script>
      

This setup ensures your Laravel 8 environment is ready and Sweet Alert is integrated for delete confirmations.

Step 2: Install Sweet Alert

Here are the steps to install SweetAlert in a Laravel 8 project:

  1. Install Laravel:

    laravel new laravel-sweetalert
    

  2. Install Laravel UI Package:

    composer require laravel/ui
    php artisan ui bootstrap --auth
    npm install && npm run dev
    

  3. Setup Database:
    Update your .env file with your database credentials:

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=laravel_sweetalert
    DB_USERNAME=root
    DB_PASSWORD=
    

  4. Install SweetAlert Package:

    composer require realrashid/sweet-alert
    

  5. Register Service Provider:
    Add the service provider to config/app.php:

    'providers' => [
        RealRashid\SweetAlert\SweetAlertServiceProvider::class,
    ],
    

  6. Add Facade:
    Add the facade to the aliases array in config/app.php:

    'aliases' => [
        'Alert' => RealRashid\SweetAlert\Facades\Alert::class,
    ],
    

  7. Publish Assets:

    php artisan sweetalert:publish
    

  8. Include SweetAlert in Blade Layout:
    Add the following line to your main Blade layout file (e.g., resources/views/layouts/app.blade.php):

    @include('sweetalert::alert')
    

  9. Use SweetAlert in Controller:
    Example of using SweetAlert in a controller method:

    use RealRashid\SweetAlert\Facades\Alert;
    
    public function store(Request $request)
    {
        // Your validation and logic here
    
        Alert::success('Success Title', 'Success Message');
        return redirect()->back();
    }
    

That’s it! You should now have SweetAlert integrated into your Laravel 8 project.

Step 3: Create a Controller

Here’s a quick guide:

  1. Create Controller:

    php artisan make:controller UsersController
    

  2. Define Routes in routes/web.php:

    Route::get('users', [UsersController::class, 'index'])->name('users.index');
    Route::delete('users/{id}', [UsersController::class, 'delete'])->name('users.delete');
    

  3. Controller Methods in app/Http/Controllers/UsersController.php:

    namespace App\Http\Controllers;
    
    use App\Models\User;
    use Illuminate\Http\Request;
    
    class UsersController extends Controller
    {
        public function index()
        {
            $users = User::all();
            return view('users.index', compact('users'));
        }
    
        public function delete($id)
        {
            User::find($id)->delete();
            return back();
        }
    }
    

  4. Blade View in resources/views/users/index.blade.php:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Users</title>
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    </head>
    <body>
        <table>
            @foreach($users as $user)
                <tr>
                    <td>{{ $user->name }}</td>
                    <td>
                        <form action="{{ route('users.delete', $user->id) }}" method="POST" class="delete-form">
                            @csrf
                            @method('DELETE')
                            <button type="submit">Delete</button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </table>
    
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script>
            document.querySelectorAll('.delete-form').forEach(form => {
                form.addEventListener('submit', function(event) {
                    event.preventDefault();
                    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) {
                            this.submit();
                        }
                    });
                });
            });
        </script>
    </body>
    </html>
    

This setup will create a controller to handle user deletion and integrate SweetAlert for confirmation.

Step 4: Set Up Routes

Here’s a concise outline for setting up routes in Laravel 8 to manage delete requests with Sweet Alert for confirmation:

  1. Install Laravel:

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

  2. Create Controller:

    php artisan make:controller UserController
    

  3. Define Routes in routes/web.php:

    Route::get('users', [UserController::class, 'index'])->name('users.index');
    Route::delete('users/{id}', [UserController::class, 'destroy'])->name('users.destroy');
    

  4. Create Delete Method in UserController:

    public function destroy($id) {
        User::findOrFail($id)->delete();
        return redirect()->route('users.index')->with('success', 'User deleted successfully');
    }
    

  5. Add Sweet Alert:

    • Install Sweet Alert:
      npm install sweetalert2
      npm run dev
      

    • Include Sweet Alert in your Blade template:
      <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
      

  6. Create Blade View for Users with Delete Button:

    @foreach ($users as $user)
        <tr>
            <td>{{ $user->name }}</td>
            <td>
                <form action="{{ route('users.destroy', $user->id) }}" method="POST" id="delete-form-{{ $user->id }}">
                    @csrf
                    @method('DELETE')
                    <button type="button" onclick="confirmDelete({{ $user->id }})">Delete</button>
                </form>
            </td>
        </tr>
    @endforeach
    
    <script>
        function confirmDelete(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.isConfirmed) {
                    document.getElementById('delete-form-' + id).submit();
                }
            })
        }
    </script>
    

This setup will allow you to manage delete requests in Laravel 8 with a Sweet Alert confirmation dialog.

Step 5: Create Blade Views

Here’s a step-by-step guide to create Blade views in Laravel 8 with Sweet Alert for delete confirmation:

  1. Install Laravel and Sweet Alert:

    composer create-project --prefer-dist laravel/laravel myapp
    composer require realrashid/sweet-alert
    

  2. Publish Sweet Alert Assets:

    php artisan vendor:publish --provider="RealRashid\SweetAlert\SweetAlertServiceProvider"
    

  3. Set Up Routes:

    // routes/web.php
    Route::get('users', [UserController::class, 'index'])->name('users.index');
    Route::delete('users/{id}', [UserController::class, 'destroy'])->name('users.destroy');
    

  4. Create Controller:

    // app/Http/Controllers/UserController.php
    namespace App\Http\Controllers;
    
    use App\Models\User;
    use Illuminate\Http\Request;
    
    class UserController extends Controller
    {
        public function index()
        {
            $users = User::all();
            return view('users.index', compact('users'));
        }
    
        public function destroy($id)
        {
            User::findOrFail($id)->delete();
            return redirect()->route('users.index')->with('success', 'User deleted successfully.');
        }
    }
    

  5. Create Blade View:

    <!-- resources/views/users/index.blade.php -->
    @extends('layouts.app')
    
    @section('content')
    <div class="container">
        @if(session('success'))
            <script>
                Swal.fire('Deleted!', '{{ session('success') }}', 'success');
            </script>
        @endif
        <table class="table">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                @foreach($users as $user)
                    <tr>
                        <td>{{ $user->name }}</td>
                        <td>{{ $user->email }}</td>
                        <td>
                            <form action="{{ route('users.destroy', $user->id) }}" method="POST" id="delete-form-{{ $user->id }}">
                                @csrf
                                @method('DELETE')
                                <button type="button" class="btn btn-danger" onclick="confirmDelete({{ $user->id }})">Delete</button>
                            </form>
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>
    
    <script>
        function confirmDelete(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.isConfirmed) {
                    document.getElementById('delete-form-' + id).submit();
                }
            })
        }
    </script>
    @endsection
    

  6. Include Sweet Alert in Layout:

    <!-- resources/views/layouts/app.blade.php -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Laravel App</title>
        <link rel="stylesheet" href="{{ asset('css/app.css') }}">
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    </head>
    <body>
        @yield('content')
        <script src="{{ asset('js/app.js') }}"></script>
    </body>
    </html>
    

This setup ensures that Sweet Alert is properly integrated for delete confirmations in your Laravel 8 Blade views.

Step 6: Implement Delete Functionality

Here’s a detailed guide on implementing delete functionality in Laravel 8 with Sweet Alert for confirmation before deletion:

Step 1: Install Laravel

First, ensure you have Laravel installed. If not, you can install it using Composer:

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

Step 2: Set Up Database

Configure your .env file with your database credentials:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password

Run the migrations to set up your database tables:

php artisan migrate

Step 3: Create a Model and Migration

Create a model and migration for the data you want to delete. For example, a Post model:

php artisan make:model Post -m

In the migration file, define the table structure:

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->timestamps();
});

Run the migration:

php artisan migrate

Step 4: Create Routes

Define routes for displaying and deleting posts in routes/web.php:

Route::get('posts', [PostController::class, 'index'])->name('posts.index');
Route::delete('posts/{id}', [PostController::class, 'destroy'])->name('posts.destroy');

Step 5: Create Controller

Create a controller to handle the logic:

php artisan make:controller PostController

In PostController, add methods for displaying and deleting posts:

public function index() {
    $posts = Post::all();
    return view('posts.index', compact('posts'));
}

public function destroy($id) {
    Post::findOrFail($id)->delete();
    return redirect()->route('posts.index')->with('success', 'Post deleted successfully');
}

Step 6: Create Views

Create a view to display posts and include a delete button. In resources/views/posts/index.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Posts</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.css">
</head>
<body>
    <h1>Posts</h1>
    @foreach($posts as $post)
        <div>
            <h2>{{ $post->title }}</h2>
            <p>{{ $post->content }}</p>
            <form action="{{ route('posts.destroy', $post->id) }}" method="POST" class="delete-form">
                @csrf
                @method('DELETE')
                <button type="submit">Delete</button>
            </form>
        </div>
    @endforeach

    <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
    <script>
        document.querySelectorAll('.delete-form').forEach(form => {
            form.addEventListener('submit', function(event) {
                event.preventDefault();
                const form = this;
                swal({
                    title: "Are you sure?",
                    text: "Once deleted, you will not be able to recover this post!",
                    icon: "warning",
                    buttons: true,
                    dangerMode: true,
                }).then((willDelete) => {
                    if (willDelete) {
                        form.submit();
                    }
                });
            });
        });
    </script>
</body>
</html>

Step 7: Test the Application

Run your Laravel application:

php artisan serve

Navigate to http://localhost:8000/posts to see the list of posts. When you click the delete button, Sweet Alert will prompt for confirmation before deleting the post.

That’s it! You’ve successfully implemented delete functionality in Laravel 8 with Sweet Alert for confirmation.

Step 7: Test the Implementation

Testing the delete confirmation functionality in Laravel 8 is crucial for several reasons:

  1. Preventing Accidental Deletions: Users might accidentally click the delete button. A confirmation dialog, especially one using Sweet Alert, ensures they have a chance to reconsider before permanently deleting data.

  2. User Experience: Sweet Alert provides a visually appealing and user-friendly way to confirm actions. Ensuring it works as expected enhances the overall user experience.

  3. Data Integrity: Confirmations help maintain data integrity by reducing the risk of unintended deletions, which can be critical in applications handling sensitive or important data.

  4. Consistency: Testing ensures that the delete confirmation behaves consistently across different browsers and devices, providing a reliable experience for all users.

  5. Error Handling: Proper testing can catch issues where the confirmation might not trigger correctly, preventing potential bugs that could lead to data loss.

Ensuring Sweet Alert works as expected involves verifying that the alert appears correctly, the confirmation and cancellation actions function properly, and any customizations (like text and styling) are applied as intended.

To Implement Delete Functionality with Sweet Alert Confirmation in Laravel 8

Follow these steps:

  1. Install Sweet Alert using npm by running npm install sweetalert2 in your terminal.
  2. Import the Sweet Alert library in your Blade template by adding <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> before the closing body tag.
  3. Create a delete form with a POST method and include the CSRF token and @method(‘DELETE’) directive to specify the HTTP request method.
  4. Add a button to submit the form, which will trigger the Sweet Alert confirmation dialog.
  5. Use JavaScript to add an event listener to the delete form that prevents default submission behavior and triggers the Sweet Alert dialog when the user clicks the delete button.
  6. In the Sweet Alert dialog, display a warning message with a title and text, and include buttons for confirmation and cancellation.
  7. When the user confirms deletion, submit the form using JavaScript.

Testing the delete confirmation functionality in Laravel 8 is crucial to ensure that it works as expected. This involves verifying that:

  • The Sweet Alert dialog appears correctly
  • The confirmation and cancellation actions function properly
  • Any customizations (like text and styling) are applied as intended

Benefits of implementing Sweet Alert for delete confirmation include preventing accidental deletions, enhancing user experience, maintaining data integrity, ensuring consistency across different browsers and devices, and handling errors.

Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *