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 User
s 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 User
s 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 User
s, for which you have a few options:
- Use
$qb->getQuery()->getArrayResult()
to get directly a plain array instead of an array ofUser
objects. - Make
User
class implementJsonSerializable
interface, so you define how the objects should be serialized. - (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 theJsonResponse
.