Mrunali Khandekar
Mrunali Khandekar

Mrunali Khandekar

How to delete record using ajax in laravel 8 and using Sweet Alerts. In Just 3 Steps.

How to delete record using ajax in laravel 8 and using Sweet Alerts. In Just 3 Steps.

Mrunali Khandekar's photo
Mrunali Khandekar

Published on Apr 24, 2021

2 min read

Subscribe to my newsletter and never miss my upcoming articles

In this article we will be using laravel 8 framework. we will see how to delete a particular record from the database in ajax and we will show a confirmation message before deleting the record.After deleting we will see how to remove the row without page refresh. Let's get started .

1) First you need to install fresh laravel project. You can refer my previous blogs to see the command used to install latest laravel project. Link mentioned below mrunali.in/logout-from-every-devices-except..

2) Set the route to display all the records I am retrieving all the users from my database.

use Illuminate\Support\Facades\DB;
Route::get('/', function () {
    // Fetch all the records from the table
    $students = DB::table('users')->where('role',0)->get();
    return view('user',compact('students'));
});

Define route to access the method delete_user in HomeController

//delete route for controller containing delete code
route::post('/delete-user',[App\Http\Controllers\HomeController::class,'delete_user']);

3) Go to HomeController app/Http/Controller/HomeController.php Write code to perform delete operation.

  public function delete_user(Request $request){
        $user = DB::table('users')->where('id',$request->id)->delete();
        return response()->json(
            [
                'success' => true,
                'message' => 'Data Deleted'
            ]
        );
    }

4) Create a blade file 'user' that will list all users in the table in resources/views/user.blade.php

@extends('layouts.app')

@section('content')
    <div id="students" class="layout-px-spacing">
        <div class="row layout-top-spacing">
            <div class="col-xl-12 col-lg-12 col-sm-12  layout-spacing">

                <div class="widget-content widget-content-area br-6">
                    <h4>Student Details</h4>
                    <div class="table-responsive mb-4 mt-4">
                        <table id="html5-extension" class="table table-hover non-hover" style="width:100%">
                            <thead>
                            <tr>
                                <th>Name</th>
                                <th>Email Id</th>
                                <th>Action</th>
                            </tr>
                            </thead>
                            <tbody id="students">
                            @foreach($students as $student)
                                <tr id="{{$student->id}}">
                                    <td>{{$student->id}}</td>
                                    <td>{{$student->email}}</td>
                                    <td ><a onclick="delete_user(this)" data-id="{{$student->id}}" id="user_delete" class="button"   data-toggle="tooltip" data-placement="top" title="" data-original-title="Delete"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-x-circle table-cancel"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></svg></a></td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

        </div>

    </div>
    <script src=
            "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>

    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

    <script type="application/javascript">

        function delete_user(e) {
            let id = e.getAttribute('data-id');
            // alert(id);
                swal({
                    title: "Are you sure?",
                    text: "Once deleted, you will not be able to recover this imaginary file!",
                    icon: "warning",
                    buttons: true,
                    dangerMode: true,
                })
                    .then((willDelete) => {
                        if (willDelete) {
                            $.ajax({
                                type:'POST',
                                url: '{{url('/delete-user')}}',
                                data:{
                                    id : id,
                                    "_token" : "{{csrf_token()}}",
                                },
                                success:function (response) {
                                    // alert("delete")
                                    swal("Poof! Your imaginary file has been deleted!", {
                                        icon: "success",
                                    });
                                    $("#"+id+"").remove(); //remove the tr without refreshing
                                }
                            }); // ajax end

                        } else {
                            swal("Your imaginary file is safe!");
                        }
                    });
        }
    </script>


@endsection

And Done load your website on browser.

 
Share this