0

I am trying to update a resource in Laravel sending a PATCH request to my controller. This is my AJAX call

    $.ajax('profile', { // Replace with your actual endpoint URL
    type: 'PATCH',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'), // CSRF token for Laravel
        // 'X-HTTP-Method-Override': 'PATCH'
    },
    data:  {status: 'some status'},
    success: function (data) {
        console.log(data);
    },
})
    .catch((error) => {
        console.error('Error:', error);
    });

And currently my Controller simply gives back the request data as a response

public function update(ProfileUpdateRequest $request)
{
 return response()->json(['message' => 'Data updated successfully', 'data' => $request->all()]);
}

I get the message 'Data updated sucessfully', the data array however, is completely empty.

I've already tried it with type: 'POST' and spoofing the method in the data array with _method: 'PATCH', which led to the message "'POST' is not a supported method for this route."

Any ideas?

EDIT: ProfileUpdateRequestClass:

namespace App\Http\Requests;

use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class ProfileUpdateRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        return [
//            'name' => ['required', 'string', 'max:255'],
//            'email' => ['required', 'string', 'email', 'max:255'],
        ];
    }
}
8
  • What's the purpose of returning $request->all()? Commented Jul 26, 2024 at 19:18
  • Just seeing if the request is properly sent to the controller and if it's filled with data. Commented Jul 26, 2024 at 19:20
  • You send only status with request to the controller. Commented Jul 26, 2024 at 19:22
  • I can use as many arguments as I want, none will be sent back. This was just an example Commented Jul 26, 2024 at 19:29
  • Are you going to update user data? Because you are using ProfieUpdateRequest. Commented Jul 26, 2024 at 19:42

1 Answer 1

0

When you set 'Content-Type': 'application/json' you must explicitly send json encoded data:

$.ajax("profile", {

    method: "PATCH",  // method is used instead of type in latest versions of JQuery
    contentType:"application/json", // there is an option to set 'Content-Type' without using headers
    headers: {
        "X-CSRF-TOKEN": "{{ csrf_token() }}" // this may be a more concise option for CSRF-TOKEN
    },

    data: '{"status": "some status"}',  // or if you prefer: JSON.stringify ({status: "some status"})

    .....

But then in your ProfileUpdateRequest you have to manually extract the data:

class ProfileUpdateRequest extends FormRequest
{
    .....

    protected function prepareForValidation()
    {
        $this->merge(json_decode($this->getContent(), associative: true));
    }

    .....

My suggestion is to leave the default contentType in the request (application/x-www-form-urlencoded; charset=UTF-8) and proceed more simply:

$.ajax("profile", {

    method: "PATCH",

    headers: {
        "X-CSRF-TOKEN": "{{ csrf_token() }}"
    },

    data: {status: "some status"},
    
    .....

In this way return response()->json(['message' => 'Data updated successfully', 'data' => $request->all()]); will provide the expected result

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.