Request::getBody(): string|null

In this article

Gets the request body.

Description

For GET requests, returns null.
For POST/PUT/PATCH requests:

  • If body is set, returns it as-is
  • If data is set and Content-Type is JSON, returns JSON-encoded data
  • If data is set and Content-Type is form, returns URL-encoded data

Return

string|null The body.

Source

public function getBody(): ?string
{
    // GET requests don't have a body
    if (!$this->method->hasBody()) {
        return null;
    }
    // If body is set, return it as-is
    if ($this->body !== null) {
        return $this->body;
    }
    // If data is set, encode based on content type
    if ($this->data !== null) {
        $contentType = $this->getContentType();
        // JSON encoding
        if ($contentType !== null && stripos($contentType, 'application/json') !== \false) {
            return json_encode($this->data, \JSON_THROW_ON_ERROR);
        }
        // Default to URL encoding for forms
        return http_build_query($this->data);
    }
    return null;
}

Changelog

VersionDescription
0.1.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.