Introduction

The purpose of this blog is to document the steps for implementing Sweet Alert, a JavaScript library by RealRashid, to confirm the deletion of a record in a Laravel controller’s destroy() method.

Prerequisites

  1. Laravel application set up.
  2. Sweet Alert library by RealRashid already included in the project.

Step 1

Include ‘sweetalert::alert’ in the master layout using below following line:

@include('sweetalert::alert');

Then, run the following command to publish the package assets:

php artisan sweetalert:publish

Step 2

Create a controller with resource perameter using the following command:

php artisan make:controller productController --resource

That generate the all the basic functions for CRUD operation.

Step 3

Add the following code in the index method of the controller:

public function index(){
        $title = 'Delete Product!';
        $text = "Are you sure you want to delete?";
        confirmDelete($title, $text);
        $products = product::select('id','title','vendor','type')->limit(10)->get();
        return view('products.list',compact('products'));
    }

Then, add the attribute data-confirm-delete=”true” to view file’s delete button :

<a href="{{ route('product.destroy', $product->id) }}" class="btn btn-danger" data-confirm-delete="true">Delete</a>

After applying this attribute to the anchor tag, when the user click on this anchor tag, the Sweet Alert confirmation popup will appear. if user confirm this action, they will be redirect to the destroy URL.

Step 4
After beging redirected to the destroy method, you have to delete the record from database using the following code:

 public function destroy(string $id){
        $product = product::find($id);
        if ($product->delete()){ 
Alert::success('Deleted', 'Product Deleted successfully');
        }
        return redirect()->route('product.index');
    }

Support On Demand!

                                         
Laravel