Search code examples
laravellaravel-routingputlaravel-api

Laravel API: validate doesn't access the PUT request data in my API


Context

I am implementing a user information update using a PUT request in Laravel 8. I use Postman to send the request and see the results.

Expected behavior

My PUT request reaches the controller's function that is censed to update the authenticated user. The latter is updated successfully. So the validate call is executed succesfully and finds the data in the request.

Actual behavior

My PUT request reaches the controller's function that is censed to update the authenticated user. The latter is not updated successfully. In fact, the validate call is executed succesfully but doesn't find the data in the request.

Instead, data validation says:

{ "message": "The given data was invalid.", "errors": { "email": [ "The email field is required." ], "name": [ "The name field is required." ] } }

The route & The request

Postman request

curl --location --request PUT 'https://XYZ/api/set_user_data' \
--header 'X-Requested-With: XMLHttpRequest' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer 12|leRLA5yopCLIxe0oN9MMThctqD78iJDjZdZQkcgs' \
--data-urlencode '[email protected]' \
--data-urlencode 'name=test2'

It means in Postman terminology that no "Params" are sent, an Authorization Bearer token is sent, some Headers are sent and some Body's x-www-form-urlencoded data are sent.

API Route

In routes/api.php:

Route::put('/set_user_data', [UserController::class, 'setUserData'])->name('set_user_data');

UserController::setUserData:

public function setUserData(Request $request) {
    if(!Auth::check()) {
        return 'unauthenticated.';
    }

    $request->validate([
        'email' => 'required|email',
        'name' => 'required|string'
    ]);

 // ... update user here but out of topic
}

What I tried to do... or to not do

  • Some Stackoverflow answers are: send a POST request and send in the body _method=PUT. I don't want to do this. I really prefer to send a PUT request. Because I am developing an API. It totally justifies the fact that I must use a PUT request and not a PUT one.

  • Some Stackoverflow answers are: use x-www-form-urlencoded not a simple form. It doesn't fix the problem; moreover it's already the case. Maybe it could help with images sending. (notice I don't want to send any image here).

Question

Why Laravel's validate don't find the data of my request and how to fix it?


Solution

  • You are sending the request as "Content-type: application/json", but you are not sending the body as valid JSON.

    You are sending this:[email protected]&name=test2

    You should send this:

    {"email":"[email protected]", "name": "test2"}

    a valid JSON object