Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}

JS

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

I am just looking for clarity, thanks!

like image 372
Rafael Avatar asked Dec 14 '22 17:12

Rafael


1 Answers

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 respond like

string(5) "PATCH"

Read more about Request Information on Laravel doc.

like image 75
Set Kyar Wa Lar Avatar answered Jan 22 '23 10:01

Set Kyar Wa Lar