PUT/PATCH request with postman returns status code 0 in Laravel

13.8k Views Asked by At

I have written some REST API Methods, including one for updating a DB entry:

// Update
public function update(CreateAEDRequest $request, $id) {
    $aed = AED::find($id);

    if(!$aed) {
        return response()->json(['message' => "Dieser AED exisitiert nicht", 'code' => 404], 404);
    }

    $owner = $request->get('owner');
    $street = $request->get('street');

    $aed->owner = $owner;
    $street->street = $street;

    $aed->save();

    return response()->json(['message' => 'Der AED wurde aktualisiert'], 200);
}

The Route is defined as:

    Route::put('/aeds/{aeds}', 'APIAEDController@update');
    Route::patch('/aeds/{aeds}', 'APIAEDController@update');

A Request is being handled by:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use Illuminate\Http\JsonResponse;

class CreateAEDRequest extends Request
{
    public function authorize()
    {
        // turn back to false when doing auth
        return true;
    }

    public function rules()
    {
        return [
            'owner'  => 'required',
            'street' => 'required'
        ];
    }

}

But when I use postman and try to update the existing DB entry and I fill in the owner and street variable to be sent in POSTMAN as requested, I get the message: "Could not get any response. Returns Status Code 0"

enter image description here

All the other methods work fine. Is the definition of my routing not correct?

Update When I send the data as x-www-form-urlencodedit works! When I send them as form-data it brings up the error message.

3

There are 3 best solutions below

0
On

In Postman

  1. Change method to POST
  2. Add new variable _method with value PUT or PATCH
1
On

It looks like in Postman you should point that the data you send is x-www-url-formurlencoded.

enter image description here

0
On

I was also struggling with this over the past few days. A colleague found out that you can gather the parameters using the input() function of the Request.

Using your Postman example, you can do the following:

Postman Example - Stackoverflow

And then in Laravel you can access the data like this:

// Not sure if you might need to swap the $id with the $request parameters.
// Try and swap them if you are not getting the correct data
public function update($id, CreateAEDRequest $request) {
    $aed = AED::find($id);

    if(!$aed) {
        return response()->json([
            'message' => "Dieser AED exisitiert nicht", 'code' => 404
          ], 404);
    }

    // USE the input() function here to read the data sent from Postman request
    $owner = $request->input('owner');
    $street = $request->input('street');

    $aed->owner = $owner;
    $street->street = $street;

    $aed->save();

    return response()->json(['message' => 'Der AED wurde aktualisiert'], 200);
}

PS: I'm using Laravel 8.65 and Postman v9.0.8