Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete record in laravel 5.3 using ajax request?

I'm trying to delete record using ajax in laravel 5.3, i know this is one of the common question and there is already lots of online solutions and tutorials available about this topic. I tried some of them but most of giving me same error NetworkError: 405 Method Not Allowed. I tried to do this task by different angle but i'm stuck and could not found where i'm wrong, that's why i added this question for guideline.

I'm trying following script for deleting the record.

Controller.php

public function destroy($id)
{   //For Deleting Users
    $Users = new UserModel;
    $Users = UserModel::find($id);
    $Users->delete($id);
    return response()->json([
        'success' => 'Record has been deleted successfully!'
    ]);
}

Routes.php

Route::get('/user/delete/{id}', 'UserController@destroy');

In View

<button class="deleteProduct" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >Delete Task</button>

App.js

$(".deleteProduct").click(function(){
        var id = $(this).data("id");
        var token = $(this).data("token");
        $.ajax(
        {
            url: "user/delete/"+id,
            type: 'PUT',
            dataType: "JSON",
            data: {
                "id": id,
                "_method": 'DELETE',
                "_token": token,
            },
            success: function ()
            {
                console.log("it Work");
            }
        });

        console.log("It failed");
    });

When i'm click on delete button it returning me error NetworkError: 405 Method Not Allowed in console. Without ajax same delete function is working properly.

Can anyone guide me where i'm wrong that i can fix the issue, i would like to appreciate if someone guide me regarding this. Thank You..

like image 331
Ayaz Ali Shah Avatar asked Sep 06 '16 13:09

Ayaz Ali Shah


People also ask

How do I delete a record in laravel?

php. Route::get('delete-records','StudDeleteController@index'); Route::get('delete/{id}','StudDeleteController@destroy'); Step 6 −The output will appear as shown in the following image. Step 7 − Click on delete link to delete that record from database.

How do you delete a request on ajax?

The working of the ajax delete request So we can use the ajax() function with type option as “$. ajax( 'http://time.jsontest.com', { type : “DELETE});”, where the first parameter is the URL of the data that to delete. So, if the request successful means that the specified data will get deleted.

How do I delete a single record in laravel 8?

Step 1: Create Controller UserController by executing this command. Step 2: We can delete records in two ways. Second Method: The second way is to delete using the Laravel delete Function and User Model (Easy one). ->name( 'users.


4 Answers

Instead of using Route::get use Route::delete.

In addition to that change the type: 'Put' to type: 'DELETE' in the ajax call.


P.S. This code

$Users = new UserModel;        // Totally useless line
$Users = UserModel::find($id); // Can chain this line with the next one
$Users->delete($id);

can be written as:

UserModel::find($id)->delete();

Or even shorter:

UserModel::destroy($id);

Keep in mind that ->delete() will fire an event while ::destroy() will not.

like image 189
siannone Avatar answered Oct 19 '22 01:10

siannone


Make sure to add this in the meta tag of your view

    <meta name="csrf-token" content="{{ csrf_token() }}">

In your Routes, do this

Route::delete('/user/delete/{id}', 'UserController@destroy');

In your controller, do this

UserModel::destroy($id);

or

DB::table('table_name')->where('id', $id)->delete();

Make sure to check that the user who is deleting the account actually owns the account a.k.a run authorization test.

Since it's a delete request, you would require to send the csrf_token along with your ajax header as the official site states. https://laravel.com/docs/5.5/csrf#csrf-x-csrf-token

Make sure to add this before the ajax call

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
});

Now send the request

$(".deleteProduct").click(function(){
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax(
    {
        url: "user/delete/"+id,
        type: 'delete', // replaced from put
        dataType: "JSON",
        data: {
            "id": id // method and token not needed in data
        },
        success: function (response)
        {
            console.log(response); // see the reponse sent
        },
        error: function(xhr) {
         console.log(xhr.responseText); // this line will save you tons of hours while debugging
        // do something here because of error
       }
    });
});

I hope this helps.

like image 39
Koushik Das Avatar answered Oct 19 '22 02:10

Koushik Das


$(".deleteProduct").click(function(){
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$.ajax(
{
    url: "user/delete/"+id,
    type: 'DELETE', // Just delete Latter Capital Is Working Fine
    dataType: "JSON",
    data: {
        "id": id // method and token not needed in data
    },
    success: function (response)
    {
        console.log(response); // see the reponse sent
    },
    error: function(xhr) {
     console.log(xhr.responseText); // this line will save you tons of hours while debugging
    // do something here because of error
   }
});

});

like image 3
Ganesh Khartode Avatar answered Oct 19 '22 02:10

Ganesh Khartode


i'm resuming a working flow of deletion, with a request VERB. Hope it helps

and theres a commented code in the controller that could handle an ajax request

In the form (with blade):

  {{ Form::open(['method' => 'DELETE', 'route' => ['admin.products.edit', $product->id], 'name' => 'delete']) }}
    {{ Form::close() }}

Route:

Route::delete('admin/products/{id}/edit', ['as' => 'admin.products.edit', 'uses' => 'Product\ProductController@delete']);

ProductController:

 public function delete($id)
    {
        // if (Request::ajax()) {
        // if (Request::isMethod('delete')){

        $item = Product::findOrFail($id);
        $item->delete();

        return redirect()->route('admin.products')->with('flashSuccess', 'deleted');
    }

In the redirect part, i'm going back to my list page (admin.products) with a success notifier. The route would be:

Route::get('admin/products', ['as' => 'admin.products', 'uses' => 'Product\ProductController@getList']);

So you can complete the flow.

like image 1
Rodrigo Butta Avatar answered Oct 19 '22 01:10

Rodrigo Butta