I would like to add a few things on top of what Vim Diesel has mentioned as the answer to his post.
As of 2021, when i followed the code's formatting I do end up with a malformed payload as the error message. To correct this I removed the query body query { } and used '"query": "query queryName{ }"'
If you do need to include variables for the GraphQL query, you can do as the following (from GraphQL documentation):
$graphQLquery = '{"query": "query { viewer { repositories(last: 100) { nodes { name id isPrivate nameWithOwner } } } } "}, "variables": { "isPrivate": "True", "name": "JohnDoe", ... }';
You can separate the query using single quotes ' and a period . in PHP to avoid hardcoding variables and for formatting as well.
Full example code below of what worked for me.
use GuzzleHttp\Client;
$name = 'JohnDoe';
$graphQLquery = '{'.
'"query": "query viewer {'.
'repositories(last: 100) {'.
'nodes {'.
'name'.
'id'.
'isPrivate'.
'nameWithOwner'.
'}'.
'}'.
'}",'.
'"variables": { "name": "'.$name.'", "id": "1", "isPrivate ": "True", "nameWithOwner": "VimDiesel"}'.
'}';'
$response = (new Client)->request('post', '{graphql-endpoint}', [
'headers' => [
'Authorization' => $token,
'Content-Type' => 'application/json'
],
'body' => $graphQLquery
]);