Method not allow (PUT) With AJAX Call in Laravel 5

2020-07-29 22:48发布

问题:

My Blade is:

{!! Form::open(['method' => 'PUT', 'id' => 'confirmTCU',
                                    'action' =>  ['TournamentUserController@confirmUser', $tournament->slug, $categoryTournament->id,$user->slug  ]]) !!}

It generates my Form:

<form method="POST" action="http://laravel.dev/tournaments/bisque/categories/1/users/admin/confirm" accept-charset="UTF-8" id="confirmTCU">
<input name="_method" type="hidden" value="PUT">
<input name="_token" type="hidden" value="tiaIHtctMbo1NwbEK8TqoKOyrN8ZSyeQELSyYL9A">

<button type="submit" class="btn btn-flat text-warning-600 btnConfirmTCU" id="confirm_bisque_1_admin" data-tournament="bisque" data-category="1" data-user="admin">
    <i class="text-danger glyphicon glyphicon-remove-sign"></i>
</button>
</form>

My AJAX is:

$('.btnConfirmTCU').on('click', function (e) {
    e.preventDefault();
    $(this).prop("disabled", true);

    var inputData = $('#formDeleteTCU').serialize();
    //var tournamentSlug      =   $(this).data('tournament');
    var categoryId          =   $(this).data('category');
    var userSlug            =   $(this).data('user');

    $.ajax(
        {
            type: 'PUT',
            url: url + '/categories/' + categoryId + '/users/' + userSlug + '/confirm',
            data: inputData,
            success: function (data) {
                        ...
            },
            error: function (data) {
                        ...
            }    
        }
    )
});

My route is:

Route::put('tournaments/{tournamentId}/categories/{categoryTournamentId}/users/{userId}/confirm', 'TournamentUserController@confirmUser');

My Controller is:

public function confirmUser($tournamentSlug, $tcId, $userSlug)
{
    $user = User::findBySlug($userSlug);
    $ctu = CategoryTournamentUser::where('category_tournament_id', $tcId)
        ->where('user_id', $user->id)->first();

    $ctu->confirmed ? $ctu->confirmed = 0 : $ctu->confirmed = 1;
    $ctu->save();
    return redirect("tournaments/$tournamentSlug/users");
}

I saw a lot of topics about it, but none resolved my issue.

As PUT is not allowed for most of browser, Laravel send it like POST, but includes a hidden field _method with PUT value.

Beside, I am able to perform DELETE actions, but not PUT...

Besides, method works perfect when not using AJAX.

Where is my problem???

回答1:

Your code should work fine, but it looks like you are serializing the wrong form. Your current code shows var inputData = $('#formDeleteTCU').serialize();, but the id for the form you've shown is confirmTCU.



回答2:

Change your ajax type from 'PUT' to 'POST', Laravel will read your parameter '_method' and will take that 'POST' like a 'PUT'.