Skip to content
Advertisement

Return data from Doctrine inside a JsonResponse object

My problem is that I want to return some data that I get from Doctrine inside a JsonResponse object. I get the data with a QueryBuilder, like this:

$qb = $this->getDoctrine()->getRepository(User::class)->createQueryBuilder('u');
$data = $qb->getQuery()->getResult();

$JSONResponse = new JsonResponse();
$JSONResponse->setData($data);

However, the data inside the JsonResponse looks empty:

data: {
    [],
    [],
    [],
    [],
    .....
}

Does anyone know how I can return the data this way correctly?

Advertisement

Answer

I think you’re getting the array of Users correctly from the DB using Doctrine (you can check that with a simple var_dump($data) after you fetch them.

However, when your put you array of Users into the JsonResponse, those objects will be serialized, and since (I guess) the properties in the User class are private, the serialization of each one is just an empty array []

You need to pass a plain array of data to JsonResponse instead of an array of Users, for which you have a few options:

  1. Use $qb->getQuery()->getArrayResult() to get directly a plain array instead of an array of User objects.
  2. Make User class implement JsonSerializable interface, so you define how the objects should be serialized.
  3. (Recommended) Generate a plain array from your User objects using some specialized serialization library like JMS Serializer (or manually if you prefer), and then put that data into the JsonResponse.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement