Search code examples
laravelpostmanjson-deserializationjsondecoder

how to decode json object in laravel which is passed as form_data in postman


In first image you can see how I am sending a json object as form data in order_details parameter

enter image description here

In second image I am getting a response while decoding it in Laravel 7

enter image description here

public function makeOrder(Request $request)
{
    $validator = Validator::make($request->all(), [
        'table_id' => 'required',
        'date' => 'required',
        'time_slot' => 'required|string',
        'product_ids' => 'required|array',
        'total_bill' => 'required'
    ]);

    if ($validator->fails()) {
        return response()->json(['error' => $validator->messages()->first(), 'code' => 404], 404);
    }

    return response()->json(['order' => json_decode($request->order_details), 'code' => 200], 200);
}

I am getting the error while decoding the json data.

json_decode() expects parameter 1 to be string, array given


Solution

  • The order details in the request body is an array, access first index and return it in the response

    return response()->json([
        'order' => json_decode($request->order_details[0]),
        'code' => 200,
    ], 200);
    

    This in turn gives this structure in postman, which I assume is what you want

    enter image description here