ajaxrestlaravelhttp-verbs

PATCH Ajax request in Laravel


Is it possible to make Ajax PATCH requests to Laravel, or am I restricted to POST? Laravel uses PATCH in input hidden fields. However, I am not using form elements—just buttons that should partially update a record when clicked (via an Ajax request).

How would the route look like for this?

Routes file

Route::patch('questions/{id}', 'QuestionController@update')->before('admin');

I am not sure if Laravel routes support PATCH.

Controller

public function update($id) {
    if (Request::ajax() && Request::isMethod('patch')) {
        //partially update record here
    }
}

JavaScript

$('div#question_preview <some button selector>').click(function (event) {
    $.ajax({
        url: 'questions/' + question_id,
        type: 'PATCH',
        data: {status: 'some status'}
    });
});

Solution

  • Yeah, it's possible. Try in your JavaScript:

    $('#div#question_preview <some button selector>').click(function() {
        $.ajax({
            url: 'questions/'+question_id,
            type: 'PATCH',
            data: {status: <SOME VALUE I WANT>, _method: "PATCH"},
            success: function(res) {
            }
        });
    });
    

    In your route:

    Route::patch('questions/{id}', 'QuestionController@update')->before('admin');
    

    In your QuestionController Controller's update method:

    dd(Request::method());
    

    You will see the response like

    string(5) "PATCH"
    

    Read more about request information in the Laravel documentation.