2

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');

3
  • this might help Commented Dec 17, 2019 at 8:48
  • What would be the expected result? The request you've shared does not contain any body Commented Oct 24, 2023 at 11:25
  • You are misunderstanding post data, query data and request content (json formatted), but in case of real json request, you can use: $request->getPayload()->all(). See symfony.com/blog/… Commented Mar 28, 2024 at 15:55

2 Answers 2

3

$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.

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

Comments

3

Because the $request is a Symfony\Component\HttpFoundation\Request you can:

$data = $request->toArray();

to get an array containing the payload.

It does JSON de-serialization under the hood when the request content is properly declared to be JSON via the respective headers.

This is the preferred Symfony way in contrast to json_decode() manually.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.