Laravel AJAX Delete Record From MySQL Table

Today, We want to share with you Laravel AJAX Delete Record From MySQL Table.In this post we will show you delete row with ajax function and php, hear for How to delete record in laravel 5.3 using ajax request? we will give you demo and example for implement.In this post, we will learn about How to Delete Record from MySQL Table with AJAX with an example.

Laravel AJAX Delete Record From MySQL Table

There are the Following The simple About Laravel AJAX Delete Record From MySQL Table Full Information With Example and source code.

As I will cover this Post with live Working example to develop Deleting item using Ajax request with DELETE and OPTIONS, so the Delete record using ajax request in Laravel Example is following below.

Step 1: Create Laravel Route:

routes/web.php

Route::delete('users/{id}', '[email protected]')->name('users.destroy');

Step 2: Laravel Controller Method:

app/Http/Controllers/UserController.php

public function destroy(User $user,$id = 0)
{
    try {
        $user = User::findOrFail($id);
        $user->delete();
    } catch (ModelNotFoundException $exception) {
        return back()->withError($exception->getMessage())->withInput();
    }
    
    Session::flash('error', trans("messages.user_list.delete"));
    return response()->json(['messages'=>trans("messages.user_list.delete")]);

    //or

    //return response()->json([
    //    'success' => 'User deleted successfully!'
    //]);
}

Step 3: View Code:

resources/views/users.php

<meta name="csrf-token" content="{{ csrf_token() }}">
<button class="deleteRecord btn btn-danger" data-id="{{ $user->id }}" ><i class="fa fa-trash-o"></i></button>

Step 4:JS Code:

resources/views/users.php

$(document).on('click','.deleteRecord',function(e){
    var user_id= $(this).attr("id");
    var parent = $(this).parent();

     if (!confirm('Do you want to delete this User?')) return;
     e.preventDefault();

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': '{{csrf_token()}}'
        }
    });
    $.ajax(
    {
        url: "user_mst/"+user_id,
        type: 'delete', // replaced from put
        dataType: "JSON",
        data: {
            "id": user_id // method and token not needed in data
        },
        success: function (response)
        {
            location.reload(true);
        },
        error: function(xhr) {
         console.log(xhr.responseText);
       }
    });
});

Angular 6 CRUD Operations Application Tutorials

Read :

Read Also:  Real time progress bar With PHP

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Laravel AJAX Delete Record From MySQL Table.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.