New in Symfony 6.3: Request Payload


Contributed by Kevin Bond
in #49614.

One of the essential features of the Symfony architecture is the usage of
the Request and Response objects. They allow to use an object-oriented approach
to get and set information in requests/responses instead of having to deal with
the underlying PHP superglobal arrays:

$request->query->get('foo'); // similar to $_GET['foo']
$request->request->get('foo'); // similar to $_POST['foo']
$request->cookies->get('foo'); // similar to $_COOKIES['foo']
$request->files->get('foo'); // similar to $_FILES['foo']

Although newcomers adapt to this workflow quickly, the $request->request->...
expression is a common source of confusion for some people (Why do you get the
request from the request?
, What is that second request?).
After many discussions about this, in Symfony 6.3 we've finally decided to
provide an alternative method to $request->request. The new method is called
getPayload() and it returns an InputBag object. The contents of this bag
are either Request::$request or Request::toArray():

// Example 1:
// the request has some POST data (e.g. `foo: bar` sent as `application/x-www-form-urlencoded`)
$request->getPayload()->all();
// returns the PHP array: ['foo' => 'bar']

// Example 2:
// the request has body contents as some JSON-encoded data (e.g. `{"foo": "bar"}`)
$request->getPayload()->all();
// returns the JSON-decoded data as a PHP array: ['foo' => 'bar']

The payload name was chosen as the closest to the payload definition in RFC 7231
and it's also the term used by debug tools in some browsers. We hope this method
will be easier to understand for both newcomers and experienced users. In any case,
we'll keep the $request->request in case you prefer it and to not break existing applications.

Sponsor the Symfony project.