Search code examples
phpsymfony4

How to convert json Request to an array in symfony?


I am trying to convert the JSON Request $request to an array.

I have output something like this:

^ Symfony\Component\HttpFoundation\Request {#45
  +attributes: Symfony\Component\HttpFoundation\ParameterBag {#74
    #parameters: array:3 [
      "_route" => "app_movie_create"
      "_controller" => "App\Controller\MovieController::create"
      "_route_params" => []
    ]
  }
  +request: Symfony\Component\HttpFoundation\ParameterBag {#96
    #parameters: []
  }
  +query: Symfony\Component\HttpFoundation\ParameterBag {#69
    #parameters: array:1 [
      "title" => "Homecoming"
    ]
  }

I have seen some tutorials giving following solutions.

 $data = json_decode($request->getContent(), true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new BadRequestHttpException('invalid json body: ' . json_last_error_msg());
        }

But I am getting null in my case.

I can do like this. $request->get('title');


Solution

  • $request->request->all() will return you an array of all the parameters that were sent along in the request. $request->query->all() will return you an array of all the query parameters that were sent.

    json_decode($request->getContent()) would only work if the person who sends the request is sending you a json string in the raw body. In your case (since you can use $request->get('title');), this wasn't happening. The request just contains some parameters and no raw json body.