Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

php - 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..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...