New in Symfony 6.3: Request Payload
April 26, 2023 • Published by Javier Eguiluz
Symfony 6.3 is backed by:
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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:
1 2 3 4
$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()
:
1 2 3 4 5 6 7 8 9
// 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.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
API bundles often used `$request->request` for this by populating it manually, causing for confusion.
This is the main motivator of the new method, with the improved name as a benefit. See also the original ticket leading to this change: https://github.com/symfony/symfony/issues/47646