php – drupal 8 commerce get product returns empty object-ThrowExceptions

Exception or error:

So i have created a few products and added some data to it:

enter image description here

In my custom route i am then trying to get all products out using the following code:

$products = \Drupal\commerce_product\Entity\Product::loadMultiple();
$response['data'] = $products;
$response['method'] = 'GET';
return new JsonResponse($response);

However this returns the following reponse:


Can anyone tell me what ive done wrong?

How to solve:

The JSON response is not encoding past the first level of depth. As far as I can tell, you cannot control that when using new JsonResponse().

One solution is to build your own data structure and encode the JSON manually. This solution uses the serializer service:

In your case, something like this should encode the full entity structure.

use Drupal\commerce_product\Entity\Product;
use Symfony\Component\HttpFoundation\JsonResponse;

$products = Product::loadMultiple([$ids]);

$response['data'] = $products;
$response['method'] = 'GET';

$serializer = \Drupal::service('serializer');
$jsonResponse = JsonResponse::fromJsonString($serializer->serialize($response, 'json'));
return $jsonResponse;

If using the ‘serializer’ it is best to provide that to the controller via dependency injection.

Leave a Reply

Your email address will not be published. Required fields are marked *